After Insert Trigger WIth MS SQL Server
-
04-03-2021 - |
質問
I think I have all my bases covered but wanted to ask someone who knows better than I. This is my syntax.
UPDATE SI
SET autoInsert = 0
FROM inserted
WHERE SI.autoInsert = SI.autoInsert
OR SI.autoInsert IS NULL;
and I want to set autoInsert = 0
where autoInsert = 1
or autoInsert IS NULL
解決
I'm going to assume you have some sort of identity or unique key column on your SI
table. (This will be a little more difficult if you haven't.)
I'm also going to assume your autoInsert
column is a BIT data type. This means the only values we can possibly have are 1, 0 or NULL. And you want the value updated to 0.
And finally, I'm going to assume you only care about updates to the autoInsert
column.
If that's all true, try this:
CREATE OR ALTER TRIGGER dbo.trg_ZeroAutoInsert
ON dbo.SI
AFTER UPDATE
AS
UPDATE dbo.SI
SET autoInsert = 0
FROM dbo.SI
INNER JOIN inserted AS i
ON SI.id = i.id ;
If, however, your autoInsert
column is an INT (or similar) data type, you can add the where clause to only cover values of 1 or NULL:
CREATE OR ALTER TRIGGER dbo.trg_ZeroAutoInsert
ON dbo.SI
AFTER UPDATE
AS
UPDATE dbo.SI
SET autoInsert = 0
FROM dbo.SI
INNER JOIN inserted AS i
ON SI.id = i.id
WHERE i.autoInsert = 1
OR i.autoInsert IS NULL ;