sql中觸發器
環境介紹:兩個表test1(var11,var12,var13)其中主鍵為(var11,var12)及表test2(var21,v22)其中主鍵是(var21,var22)分別與test1中的var11,var12對應.現在是要求創建一個觸發器使得在刪除test1的項目把test2中相應的項也刪除掉.
------解决方案--------------------如果是SQL SERVER 2000及其以上版本:
使用关系的级联删除就可以了。
如果是SQL SERVER 7.0或者更低的版本:
不能在两张表中建立主外键的关系,同时在test1上建立触发器:
CREATE TRIGGER [cas_del] ON [test1]
FOR DELETE
AS
delete test2 from test2 join deleted on test2.var21 = deleted.var11 and test2.var22 = deleted.var12
------解决方案--------------------CREATE TABLE TEST1 (VAR11 NCHAR(10),VAR12 NCHAR(10),VAR13 NCHAR(10))
INSERT TEST1 SELECT 'A ', 'B01 ', 'AFAFAFDSAF '
INSERT TEST1 SELECT 'A ', 'B02 ', 'AFAFAFDSAF '
--SELECT * FROM TEST1
GO
CREATE TABLE TEST2 (VAR21 NCHAR(10),VAR22 NCHAR(10),VAR23 NCHAR(10))
INSERT TEST2 SELECT 'A ', 'B02 ', 'AFAFAFDSAF '
--SELECT * FROM TEST2
GO
CREATE TRIGGER TR_TEST1 ON TEST1 FOR DELETE
AS
BEGIN
DELETE TEST2 FROM TEST2 T,DELETED D WHERE T.VAR21=D.VAR11 AND T.VAR22=D.VAR12
END
GO
DELETE FROM TEST1 WHERE VAR11= 'A ' AND VAR12= 'B02 '
SELECT * FROM TEST1
SELECT * FROM TEST2
DROP TRIGGER TR_TEST1
DROP TABLE TEST1,TEST2