日期:2014-05-18  浏览次数:20589 次

触发器的执行顺序
表1有多个update触发器 tg1,tg2,tg3 
因为考虑将来维护性,不想把3个合在一起。
所以我我知道他们的执行顺序怎么定的?

------解决方案--------------------
sp_settriggerorder 可指定第一个和最后一个执行的触发器,其他未指定的会随机触发。
------解决方案--------------------
SQL code
USE TEMPDB
GO
IF OBJECT_ID('TB') IS NOT NULL DROP TABLE TB
IF OBJECT_ID('TB2') IS NOT NULL DROP TABLE TB2
GO
CREATE TABLE TB(COL1 INT)
CREATE TABLE TB2(ID INT IDENTITY(1,1),COL1 INT)
GO
CREATE TRIGGER TIG_TB_1 ON TB
FOR INSERT
AS
BEGIN
INSERT INTO TB2
SELECT COL1+1 FROM INSERTED
END
GO
CREATE TRIGGER TIG_TB_2 ON TB
FOR INSERT
AS
BEGIN
INSERT INTO TB2
SELECT COL1+2 FROM INSERTED
END
GO
CREATE TRIGGER TIG_TB_3 ON TB
FOR INSERT
AS
BEGIN
INSERT INTO TB2
SELECT COL1+3 FROM INSERTED
END
GO
INSERT INTO TB
SELECT 1
GO
SELECT * FROM TB2
/*
1    2
2    3
3    4
*/

------解决方案--------------------
SQL code
USE TEMPDB
GO
IF OBJECT_ID('TB') IS NOT NULL DROP TABLE TB
IF OBJECT_ID('TB2') IS NOT NULL DROP TABLE TB2
GO
CREATE TABLE TB(COL1 INT)
CREATE TABLE TB2(ID INT IDENTITY(1,1),COL1 INT)
GO
CREATE TRIGGER TIG_TB_1 ON TB
FOR INSERT
AS
BEGIN
INSERT INTO TB2
SELECT COL1+1 FROM INSERTED
END
GO
CREATE TRIGGER TIG_TB_3 ON TB
FOR INSERT
AS
BEGIN
INSERT INTO TB2
SELECT COL1+3 FROM INSERTED
END
GO
CREATE TRIGGER TIG_TB_2 ON TB
FOR INSERT
AS
BEGIN
INSERT INTO TB2
SELECT COL1+2 FROM INSERTED
END
GO
INSERT INTO TB
SELECT 1
GO
SELECT * FROM TB2
/*
1    2
2    4
3    3
*/

------解决方案--------------------
如果不存在相互的引用关系,即tg2要引用tg1的结果的情形,执行先后没有关系,多个触发器是在一个事务里面,如果有一个rollback,全部会取消