一,新增引发触发器:
CREATE trigger db1moteadd on jxc_dj_kc_db_1
for insert
as
insert into jxc_dj_kc_db_1_MoteAdd(djdh,yyyymmdd,ck_out,ck_in) select inserted.dh,inserted.yyyymmdd,inserted.bm_ck,
inserted.bm_ck1 from inserted
where not exists (select * from jxc_dj_kc_db_1_MoteAdd where jxc_dj_kc_db_1_MoteAdd.djdh=inserted.dh)
二,删除引发触发器:
CREATE trigger db2moteadd on jxc_dj_kc_db_1
for delete
as
delete jxc_dj_kc_db_1_MoteAdd where jxc_dj_kc_db_1_MoteAdd.djdh in(select dh from deleted)
三,修改引发触发器:
CREATE trigger db3moteadd on jxc_dj_kc_db_1
for update
as
update jxc_dj_kc_db_1_MoteAdd set jxc_dj_kc_db_1_MoteAdd.yyyymmdd=inserted.yyyymmdd,jxc_dj_kc_db_1_MoteAdd.ck_out
=inserted.bm_ck,jxc_dj_kc_db_1_MoteAdd.ck_in=inserted.bm_ck1 from jxc_dj_kc_db_1_MoteAdd inner join inserted
on jxc_dj_kc_db_1_MoteAdd.djdh=inserted.dh
四,新增、删除、修改写成同一个触发器(可用于单向同步数据内容):
CREATE trigger db1moteadd on jxc_dj_kc_db_1
for insert,delete,update
as
begin
if exists (select * from inserted) and not exists (select * from deleted)
insert into jxc_dj_kc_db_1_MoteAdd(djdh,yyyymmdd,ck_out,ck_in,is_check)
select inserted.dh,inserted.yyyymmdd,inserted.bm_ck,inserted.bm_ck1,inserted.is_check from inserted
where not exists (select * from jxc_dj_kc_db_1_MoteAdd where jxc_dj_kc_db_1_MoteAdd.djdh=inserted.dh)
end
begin
if not exists (select * from inserted) and exists (select * from deleted)
delete jxc_dj_kc_db_1_MoteAdd where jxc_dj_kc_db_1_MoteAdd.djdh in(select dh from deleted)
end
begin
if exists (select * from inserted) and exists (select * from deleted)
update jxc_dj_kc_db_1_MoteAdd set jxc_dj_kc_db_1_MoteAdd.yyyymmdd=inserted.yyyymmdd,jxc_dj_kc_db_1_MoteAdd.ck_out
=inserted.bm_ck,jxc_dj_kc_db_1_MoteAdd.ck_in=inserted.bm_ck1,jxc_dj_kc_db_1_MoteAdd.is_check
=inserted.is_check from jxc_dj_kc_db_1_MoteAdd inner join inserted on jxc_dj_kc_db_1_MoteAdd.djdh=inserted.dh
end
////////参考转载资料///////////////////
可以根据从下面方法判断触发器是是处理了插入,删除还是更新触发的:
--宣告两个变量
DECLARE @D BIT = 0
DECLARE @I BIT = 0
--如果在DELETED内部临时触发表找到记录,说明旧数据被删除
IF EXISTS(SELECT TOP 1 1 FROM DELETED)
SET @D = 1
--如果在INSERTED内部临时触发表找到记录,说明有新数据插入
IF EXISTS(SELECT TOP 1 1 FROM INSERTED)
SET @I = 1
--如果两个表都有记录,说明触发器是执行更新触发
IF @I = 1 AND @D = 1
PRINT(N更新 。)
--如果变量@I值被变更为1,而变量@D没有变更,说明触发器是执行插入触发
IF @I = 1 AND @D = 0
PRINT(N插入)
--下面判断成立,说明说明触发器是执行删除触发
IF @I = 0 AND @D = 1
PRINT(N删除)
另外有关两个内部临时触发表,触发器的Inserted表和Deleted表
触发器有两个虚拟表,Inserted表和Deleted表,这两个表在不同操作情况之下,表中的数据状态可不一样 。
一、插入操作(INSERT)时:Inserted表有数据,Deleted表无数据 。
二、更新操作(UPDATE)时:Inserted表有数据(新数据),Deleted表有数据(旧数据) 。
三、删除操作(DELETE)时:Inserted表无数据,Deleted表有数据 。
但是有时候,可以视看处进逻辑程度,可以把三者写成一个触发器,只是在其中稍作判断而已。 |
|