如何检查此触发器中更新的字段值:
ALTER TRIGGER dbo.OrderApprovedSms
ON dbo.[Order]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
/*How can check approve date is updated*/
IF (/*ApproveDate is updated*/)
BEGIN
INSERT INTO office.SmsSendBuffer
( Number ,
Body
)
SELECT 'xxxxxx','ORDER APPROVED!'
END
END
答案 0 :(得分:3)
这将是:
ALTER TRIGGER dbo.OrderApprovedSms
ON dbo.[Order]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO office.SmsSendBuffer
( Number ,
Body
)
SELECT 'xxxxxx','ORDER APPROVED!' --No columns from inserted or deleted?
FROM inserted i INNER JOIN deleted d
ON i.<primary key column 1> = d.<primary key column 1> AND
i.<primary key column 2> = d.<primary key column 2> AND
i.ApprovedDate != d.ApprovedDate --Not sure what actual check you wanted to perform
END
其中deleted
and inserted
是伪表,其中包含UPDATE
语句影响的行(对应于语句之前和之后的状态)
有一个名为UPDATE
的函数可以回答“此列在此UPDATE
语句中是否受到更新的问题?”但它a)inserted
和deleted
和b)中只有行的整个集的答案不会让您区分那些没有实际效果的更新(例如,如果您SET Column=2
Column
已经2
已经Column
,它仍会回答UPDATE
已更新)
作为我认为create table T (ID int not null,Col1 int not null)
go
create trigger TT on T after update
as
IF UPDATE(Col1)
BEGIN
RAISERROR('Hello',10,1) WITH NOWAIT
END
go
update T set Col1 = Col1
函数无意义的一个例子,请考虑以下内容:
Hello
在输出中打印UPDATE
- 因此,我们有0
影响{{1}}行(因为该表是新的),即使有任何行,也不会改变了任何数据。
答案 1 :(得分:1)
使用inserted
表,它将包含新行。 deleted
将包含旧行。
答案 2 :(得分:0)
你可以这样做......
INSERT INTO TargetTable(Col1, COl2, Col3)
SELECT t.Col1, t.COl2, t.Col3
FROM TableName t
WHERE EXISTS
(
SELECT 1
FROM inserted i INNER JOIN deleted d
ON i.PK_Col = d.PK_Col
WHERE i.Date_Col <> d.Date_Col
AND d.PK_Col = t.PK_Col
)
答案 3 :(得分:0)
注意: - 将此作为单独的评论发布,因为我没有足够的积分来添加评论。
你有两个选项,UPDATE()和COLUMNS_UPDATED()。发布使用UPDATE()函数的示例脚本,为UPDATE()和COLUMNS_UPDATED()提供外部链接。有关详细说明,请查看这些链接。
use TempDb
Go
create table test ( n1 int , n2 int , n3 int )
go
create table testCopy ( n1 int , n2 int , n3 int )
go
create trigger TestTrg
on test
after update
as
if update(n3) -- This is the key function
-- http://technet.microsoft.com/en-us/library/ms186329.aspx -- COLUMNS_UPDATED()
-- http://technet.microsoft.com/en-us/library/ms187326.aspx -- UPDATE()
insert into testCopy (n3 ) select n3 from deleted
go
insert into test values ( 1, 2, 3 ) ,( 2, 3, 4)
go
update test set n2 = n2 + 1 -- no values would be inserted into testcopy
update test set n1 = n1 + 1 -- no values would be inserted into testcopy
update test set n3 = n3 +1 where n3 = 3 -- one row will be inserted into test copt
答案 4 :(得分:0)
这很简单,您可以使用UPDATE函数来检查字段值更新。
ALTER TRIGGER dbo.OrderApprovedSms
ON dbo.[Order]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
/*How can check approve date is updated*/
IF (UPDATE (ApproveDate))
BEGIN
INSERT INTO office.SmsSendBuffer
( Number ,
Body
)
SELECT 'xxxxxx','ORDER APPROVED!'
END
END