sql server触发器:表A有a,b,c,d,e5个字段,表B有a,c,e3个字段,触发器实现对表A进行增加,删除操作时,表
2个回答
展开全部
create trigger trig_test
on 表A
for insert,update,delete
as
begin
--判断是insert
if exists(SELECT 1 FROM inserted) AND NOT EXISTS(SELECT 1 FROM deleted)
begin
insert into 表B select a,c,e from inserted
end
--判断修改
if exists(SELECT 1 FROM inserted) AND EXISTS(SELECT 1 FROM deleted)
begin
update b set b.c=i.c,b.e=i.e
from 表b inner join inserted i
on i.a=b.a
end
--判断删除
if exists(SELECT1FROM inserted) ANDEXISTS(SELECT1FROM deleted)
begin
delete from 表B where B.a in (select a from deleted)
end
end
适用于 单条或多条删除,修改,增加
写完了才看到有人回答了···。蛋疼,灰常疼
on 表A
for insert,update,delete
as
begin
--判断是insert
if exists(SELECT 1 FROM inserted) AND NOT EXISTS(SELECT 1 FROM deleted)
begin
insert into 表B select a,c,e from inserted
end
--判断修改
if exists(SELECT 1 FROM inserted) AND EXISTS(SELECT 1 FROM deleted)
begin
update b set b.c=i.c,b.e=i.e
from 表b inner join inserted i
on i.a=b.a
end
--判断删除
if exists(SELECT1FROM inserted) ANDEXISTS(SELECT1FROM deleted)
begin
delete from 表B where B.a in (select a from deleted)
end
end
适用于 单条或多条删除,修改,增加
写完了才看到有人回答了···。蛋疼,灰常疼
更多追问追答
追问
谢谢啊!第一个回答的有点小问题,你考虑的比较完善。不过
--判断删除
if exists(SELECT1FROM inserted) ANDEXISTS(SELECT1FROM deleted)
这里第一个应该是 not exists吧
追答
对的,楼主很会举一反三。 确实写错了,赢是not exists
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
create trigger tr_a_b_ins_up_del
on a
after insert,update,delete
as
if exists(select * from inserted) and exists(select * from deleted) begin
update b set b.a=a.a,b.c=a.c,b.e=a.e from inserted a where a.id=a.id
--如果没有id可以批评,只能再关联deleted表然后与b表匹配ace三个值
end
if exists(select * from inserted) begin
insert into b(a,c,e) select a,c,e from inserted
end
else begin
delete b where id in (select id from deleted)
--如果没有id匹配可以用ace三个值
--delete b where a+c+e in (select a+c+e from deleted)
end
on a
after insert,update,delete
as
if exists(select * from inserted) and exists(select * from deleted) begin
update b set b.a=a.a,b.c=a.c,b.e=a.e from inserted a where a.id=a.id
--如果没有id可以批评,只能再关联deleted表然后与b表匹配ace三个值
end
if exists(select * from inserted) begin
insert into b(a,c,e) select a,c,e from inserted
end
else begin
delete b where id in (select id from deleted)
--如果没有id匹配可以用ace三个值
--delete b where a+c+e in (select a+c+e from deleted)
end
更多追问追答
追问
if exists(select * from inserted) and exists(select * from deleted) begin
update b set b.a=a.a,b.c=a.c,b.e=a.e from inserted a where a.id=a.id
这2行能详细解释下吗 ,我第一次写触发器
追答
触发器中有inserted与deleted两个专用表,inserted记录插入的数据,当update时为更新的数据
deleted记录删除的数据,当update时记录旧数据
综上,当同时存在inserted与deleted记录时状态为update
只存在inserted状态为插入,最后一种情况为delete
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询