I would write two triggers - one for UPDATE
, another for INSERT
- if you try to do this in a single trigger, the code gets messy because of the checks for "is this an INSERT or UPDATE operation?" etc. - don't do that....
AFTER UPDATE
trigger:
CREATE TRIGGER dbo.TrgEventsConfigUpdate
ON dbo.EventsConfig
AFTER UPDATE
AS
UPDATE insp
SET IsRepaired = 1
FROM dbo.Inspections insp
INNER JOIN Inserted i ON i.InspectionId = insp.Id
INNER JOIN Deleted d ON d.Id = i.Id
WHERE i.[Event] = -1 AND d.[Event] <> -1
Basically, after an update, you need to look at the Inserted
and Deleted
pseudo tables which contain the updated rows - if the new row (after the update) has a value of -1, while the old row (before the update) did not --> then the column Event
has been updated to -1 and thus the IsRepaired
in the table Inspections
needs to be set to 1
(true).
AFTER INSERT
trigger:
CREATE TRIGGER dbo.TrgEventsConfigInsert
ON dbo.EventsConfig
AFTER INSERT
AS
UPDATE insp
SET IsRepaired = 1
FROM dbo.Inspections insp
INNER JOIN Inserted i ON i.InspectionId = insp.Id
WHERE i.[Event] = -1
Same idea - just a bit simpler, since there's no "old" row to compare to: if the column in the list of inserted rows has a value of -1, then update the Inspections
table for those InspectionId
values to be 1
.