Sql-Server

檢查觸發器是否由 INSERT 或 DELETE 觸發

  • January 10, 2018

我知道這是您可以在此網站上找到的最簡單的問題,但我無法在網際網路上找到它的答案。

如何檢查觸發器是否由INSERTor觸發DELETE

例子

CREATE TRIGGER [dbo].[TestTrigger]
On [dbo].[Table1]
AFTER INSERT, DELETE
AS
   --if save
   --do some work

   --else if delete
   --do some work other work

如果是插入,我想做一些工作,如果是刪除,我想做一些其他工作。

請提供相同的程式碼片段。

只要觸發器僅用於插入/刪除:

IF EXISTS (SELECT 1 FROM inserted)
  -- I am an insert
ELSE
  -- I am a delete

事實上,如果你基於插入/刪除的連接做事情,它可以更簡單:

-- do something for an insert
-- this will only actually do anything when it's an insert
INSERT dbo.somewhereElse SELECT whatever, 'insert'
 FROM dbo.sourceTable AS s
 INNER JOIN inserted AS i ON s.id = i.id;

-- do something for a delete
-- this will only actually do anything when it's a delete
INSERT dbo.somewhereElse SELECT whatever, 'delete'
 FROM dbo.sourceTable AS s
 INNER JOIN deleted AS d ON s.id = d.id;

如果將更新操作添加到觸發器,邏輯會變得更加複雜,當然:

IF EXISTS (SELECT 1 FROM inserted)
BEGIN
 IF EXISTS (SELECT 1 FROM deleted)
 BEGIN
   -- I am an update
 END
 ELSE
 BEGIN
   -- I am an insert
 END
END
ELSE
BEGIN
 -- I am a delete
END

引用自:https://dba.stackexchange.com/questions/137862