原文連接:http://blog.csdn.net/baronyang/article/details/5174734 php
原來update觸發器只會被update觸發一次,不管更新的記錄數是多少,如下爲驗證代碼ide
[php] view plaincopyurl
CREATE TABLE TMP_TABLE1 (PersonCode VARCHAR(20) NOT NULL PRIMARY KEY,[NAME] VARCHAR(50) NULL,DepCode VARCHAR(20) NULL,Amount MONEY null) spa
CREATE TABLE TMP_TABLE2 (PersonCode VARCHAR(20) NOT NULL PRIMARY KEY,[NAME] VARCHAR(50) NULL,DepCode VARCHAR(20) NULL,Amount MONEY null) .net
GO code
INSERT INTO TMP_TABLE1(PersonCode,[NAME],Amount) orm
VALUES('00001','AAA1',1000) blog
INSERT INTO TMP_TABLE1(PersonCode,[NAME],Amount) ip
VALUES('00002','AAA2',1000) get
INSERT INTO TMP_TABLE1(PersonCode,[NAME],Amount)
VALUES('00003','AAA3',1000)
INSERT INTO TMP_TABLE1(PersonCode,[NAME],Amount)
VALUES('00004','AAA4',1000)
INSERT INTO TMP_TABLE1(PersonCode,[NAME],Amount)
VALUES('00005','AAA5',1000)
INSERT INTO TMP_TABLE2(PersonCode,[NAME],Amount)
VALUES('00001','AAA1',1000)
INSERT INTO TMP_TABLE2(PersonCode,[NAME],Amount)
VALUES('00002','AAA2',1000)
INSERT INTO TMP_TABLE2(PersonCode,[NAME],Amount)
VALUES('00003','AAA3',1000)
INSERT INTO TMP_TABLE2(PersonCode,[NAME],Amount)
VALUES('00004','AAA4',1000)
INSERT INTO TMP_TABLE2(PersonCode,[NAME],Amount)
VALUES('00005','AAA5',1000)
GO
Alter TRIGGER dbo.tmp_table1_update ON tmp_table1
AFTER UPDATE
AS
SELECT * INTO #INS FROM INSERTED
DECLARE @PersonCode VARCHAR(20),@Amount MONEY
IF UPDATE(Amount)
BEGIN
SELECT @personcode=personcode,@Amount=Amount FROM #INS
UPDATE TMP_TABLE2 SET Amount =@Amount WHERE PersonCode=@PersonCode
END
GO
UPDATE TMP_TABLE1 SET Amount = 2000
select * from TMP_TABLE1
SELECT * FROM TMP_TABLE2
而後再更新,發現TMP_TABLE1的Amount字段值都更新爲2000,但TMP_TABLE2的Amount值只有第一條記錄更新了,下面改一下觸發器
Alter TRIGGER dbo.tmp_table1_update ON tmp_table1
AFTER UPDATE
AS
SELECT * INTO #INS FROM INSERTED
DECLARE @PersonCode VARCHAR(20),@Amount MONEY
IF UPDATE(Amount)
BEGIN
DECLARE AmountCursor CURSOR FOR
SELECT personcode,Amount FROM #INS
OPEN AmountCursor
FETCH NEXT FROM AmountCursor INTO @PersonCode,@Amount
WHILE @@FETCH_STATUS=0--0爲Fetch語句已成功,-1爲Fetch語句失敗或不在結果集中,-2提取的行不存在
BEGIN
UPDATE TMP_TABLE2 SET Amount =@Amount WHERE PersonCode=@PersonCode
FETCH NEXT FROM AmountCursor INTO @PersonCode,@Amount
END
CLOSE AmountCursor
DEALLOCATE AmountCursor
END
更新觸發器後,一切正常。
總結:爲了保險起見,update觸發器仍是要用遊標來處理,才能保證所有觸發執行.