我想创建一个更新触发器,以检查状态列值是否已更改,例如从Pending(10)更改为Live(13)。这会将LiveDate
列更新为GETDATE()
。但是,当状态再次从Live更改为进程中的下一个状态(即状态不等于13)时,它将LiveDate设置为null。
例如待定->实时(LiveDate设置正确)->封闭(LiveDate设置为null)。
ALTER TRIGGER [dbo].[trigger_livedate]
ON [DB].[dbo].[Table1]
AFTER UPDATE
AS
UPDATE dbo.Table1
SET LiveDate = GETDATE()
FROM dbo.Table1 T
INNER JOIN INSERTED I ON T.Id = I.Id
INNER JOIN DELETED D ON T.Id = D.Id
WHERE I.StateID = 13 AND D.LiveDate IS NULL
我尝试了最后的null检查,看是否已设置LiveDate
,但仍然没有乐趣。
答案 0 :(得分:2)
如果要检查特定的转换,请同时使用deleted
表:
CREATE TRIGGER [dbo].[trigger_livedate]
ON [DB].[dbo].[Table1]
AFTER UPDATE
AS
UPDATE dbo.Table1
SET LiveDate = GETDATE()
FROM dbo.Table1 T
INNER JOIN INSERTED I ON T.Id = I.Id
INNER JOIN DELETED D ON T.Id = D.Id
WHERE I.StateID = 13 AND D.StateID = 10
如果您要在问题中表达的是“一旦设置LiveDate
,它就不会被取消设置”,那么请在您的SET
行:
SET LiveDate = COALESCE(LiveDate,GETDATE())
(但这不会阻止 other 操作将LiveDate
设置为NULL
,如果该触发器未将其设置的话)
答案 1 :(得分:0)
您还需要使用DELETED
表,以检查更新后的值。
CREATE TRIGGER [dbo].[trigger_livedate] ON [DB].[dbo].[Table1]
AFTER UPDATE
AS
UPDATE dbo.Table1
SET LiveDate = GETDATE()
FROM dbo.Table1 Tab
JOIN INSERTED Ins ON Tab.ID = Ins.ID
JOIN DELETED Del ON Tab.ID = Del.ID
WHERE Ins.StateID = 13
AND Del.StateID = 10