而不是在删除之前触发

时间:2011-04-23 09:31:55

标签: sql-server-2005

假设在删除之前我有一个而不是触发表。所以我只是想知道我是否发出删除然后在删除之前触发将触发?

还告诉我如何从删除前删除数据而不是触发器。任何人都可以通过示例代码向我展示。

1 个答案:

答案 0 :(得分:2)

它会触发而不是删除。如果您没有自己实现它,则不会删除任何内容。这些触发器通常用于Views而不是Tables。

CREATE TABLE T(
C INT IDENTITY(1,1) PRIMARY KEY,
D INT)

INSERT INTO T (D)
SELECT 1 UNION ALL SELECT 2

GO

CREATE TRIGGER tr ON T
INSTEAD OF DELETE 
AS
BEGIN 
PRINT 'Do Nothing'
END

GO

DELETE 
FROM T

SELECT * 
FROM T     /*The 2 rows are still there*/

GO         /*Implement the trigger*/

ALTER TRIGGER tr ON T
INSTEAD OF DELETE 
AS
BEGIN 
DELETE T
FROM T 
JOIN DELETED D 
ON T.C = D.C
END

GO

DELETE 
FROM T

SELECT * 
FROM T      /*The 2 rows are now gone*/

DROP TABLE T