我有一个表,它有一个bit
列和一个相应的datetime2
列,用于跟踪该标志的设置时间:
CREATE TABLE MyTable
(
Id int primary key identity,
Processed bit not null,
DateTimeProcessed datetime2
)
我添加了一个检查约束,如下所示:
ALTER TABLE MyTable
ADD CHECK ((Processed = 0 AND DateTimeProcessed IS NULL)
OR (Processed = 1 AND DateTimeProcessed IS NOT NULL))
我尝试DateTimeProcessed
使用AFTER UPDATE
触发器控制列的设置:
CREATE TRIGGER tr_MyTable_AfterUpdate ON MyTable
AFTER UPDATE
AS
BEGIN
IF(UPDATE(Processed))
BEGIN
UPDATE MyTable
SET DateTimeProcessed = CASE
WHEN tab.Processed = 1 THEN GETDATE()
ELSE NULL
END
FROM MyTable tab
JOIN INSERTED ins
ON ins.Id = tab.Id
END
END
这样做的问题是在AFTER UPDATE
触发器运行之前强制执行检查约束,因此在更新列时违反了约束Processed
。
实现我在这里尝试做的最好方法是什么?