SQL中触发器的代码写在哪里

如题所述

第1个回答  推荐于2016-02-14

里分别创建三个触发器,分别是插入、修改、删除时触发:
--插入触发器
CREATE TRIGGER TR_INSERT ON B1
FOR INSERT
AS
IF (SELECT COUNT(*) FROM INSERTED)>=1
BEGIN
INSERT K2.dbo.B2(T3,T4) SELECT T1,T2 FROM INSERTED
END
GO
--删除触发器
CREATE TRIGGER TR_DELETE ON B1
FOR DELETE
AS
IF (SELECT COUNT(*) FROM DELETED)>=1
BEGIN
DELETE K2.dbo.B2 WHERE K2.dbo.B2.T3=(SELECT T1 FROM DELETED) AND K2.dbo.B2.T4=(SELECT T2 FROM DELETED)
END
GO
--修改触发器
CREATE TRIGGER TR_UPDATE ON B1
FOR UPDATE
AS
UPDATE K2.dbo.B2 SET T3=(SELECT T1 FROM INSERTED), T4=(SELECT T2 FROM INSERTED)
WHERE T3=(SELECT T1 FROM DELETED) AND T4=(SELECT T2 FROM DELETED)

GO
--测试数据
insert into B1 values('1','2')
select * from K1.dbo.B1
SELECT * FROM K2.DBO.B2

UPDATE B1 SET T1='4' WHERE T1='1'
select * from K1.dbo.B1
SELECT * FROM K2.DBO.B2

DELETE B1 WHERE T1='4'
select * from K1.dbo.B1
SELECT * FROM K2.DBO.B2

本回答被提问者采纳
相似回答