SQL Server触发器

A表添加数据时触发“InfoAdd_A”触发器,单触发器中在添加A表数据时,不会再次触发“InfoAdd_A”触发器

--A表
create trigger InfoAdd_A--触发器名称
on A --表名
after insert--A表添加完数据之后触发
as
begin--开始执行
begin transaction triUpdate --设置起点
declare @id int,@id2 int,@id3 int,@name nvarchar(50),@Sex nvarchar(50),@Age nvarchar(50),@state nvarchar(50);--定义需要字段
--赋值
--获取更新后数据=触发当前操作的数据
select
@id=ID,
@name=Name,
@state=state
FROM INSERTED--获取触发数据
--判断B表和C表是否存在ID为@id的数据
if not exists(select * from B  where ID=@id)
begin
select @id2=-1;
end
if not exists(select * from C  where ID=@id)
begin
select @id3=-1;
end
if @id2=-1 or @id3=-1
begin
raiserror(‘B表和C表数据不存在‘,1,1)--报错!
rollback transaction triUpdate;  --数据回滚不予添加
end
else
begin
--获取信息添加数据
select @Sex=Sex from B where ID=@id
select @Age=Age from C where ID=@id
insert into S values(@name,@Sex,@Age);
commit transaction triUpdate;  --事务提交
end
END
GO

事务(tran=transaction)

  • begin tran:设置起点
  • commit tran:使事务成为数据库中永久的、不可逆转的一部分
  • rollback tran:本质上说想要忘记它曾经发生过
  • save tran:创建一个特定标记,只允许部分回滚

sqlServer 日期转化

SQL Server触发器

原文:https://www.cnblogs.com/LanHai12/p/15258221.html

以上是SQL Server触发器的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>