I have a table which has a bit
column and a corresponding datetime2
column which tracks when that flag was set:
CREATE TABLE MyTable
(
Id int primary key identity,
Processed bit not null,
DateTimeProcessed datetime2
)
I've added a check constraint as follows:
ALTER TABLE MyTable
ADD CHECK ((Processed = 0 AND DateTimeProcessed IS NULL)
OR (Processed = 1 AND DateTimeProcessed IS NOT NULL))
I attempted to control setting of the DateTimeProcessed
column using an AFTER UPDATE
trigger:
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
The problem with this is that the check constraint is enforced before the AFTER UPDATE
trigger runs, so the constraint is violated when the Processed
column is updated.
What would be the best way to achieve what I am trying to do here?