MSSQL:
解释
插入操作(Insert):Inserted表有数据,Deleted表无数据
删除操作(Delete):Inserted表无数据,Deleted表有数据
更新操作(Update):Inserted表有数据(新数据),Deleted表有数据(旧数据)
CREATE TRIGGER [dbo].[TR_TEST]
ON [dbo].[TEST]
FOR INSERT,DELETE,UPDATE
AS
BEGIN
--新增
if(exists(select 1 from inserted) and not exists(select 1 from deleted))
begin
INSERT INTO TEST2
( ID,NAME,DATATIME
)
SELECT A.ID,B.NAME,GETDATE()
FROM Inserted AS A
TAB2 B
WHERE A.ID=B.ID;
end
--删除
if(not exists(select 1 from inserted) and exists(select 1 from deleted))
begin
delete from TEST2
where ID in(select ID from deleted);
end
--更新
if(exists(select 1 from inserted) and exists(select 1 from deleted))
begin
update TEST2 set NAME=a.ID
,DATATIME=getdate()
from inserted a
where ID=a.ID;
end
END
GO