如何判断是插入还是更新

Ram*_*h S 5 trigger sql-server-2008 insert update

每当在 CUSTOMER 表中发生 INSERT 时,我需要调用“ StoredProcedure1 ”并且在 CUSTOMER 表中发生 UPDATE,我需要在触发器中调用“ StoredProcedure2 ”。 如何确定是在 SQL Server 2008的触发器中插入还是更新

有人可以请帮我如何解决?

代码:

CREATE TRIGGER Notifications ON CUSTOMER
FOR INSERT,UPDATE
AS
BEGIN
DECLARE @recordId varchar(20);
set @recordId= new.Id;
    //if trigger is insert at the time I call to SP1
        EXEC StoredProcedure1 @recordId
    //if trigger is Upadeted at the time I call to SP2
        EXEC StoredProcedure2 @recordId
END
Run Code Online (Sandbox Code Playgroud)

Aar*_*and 10

因为只有UPDATE,INSERT你可以说:

IF EXISTS (SELECT 1 FROM deleted)
  -- update
ELSE
  -- insert
Run Code Online (Sandbox Code Playgroud)

不过,你有一个更大的问题。没有new.Id, 并且插入或更新可以影响多行(在某些平台中,触发器每行触发;在 SQL Server 中,它们按操作触发)。所以你需要:

  1. 使用循环调用存储过程为所有的的RecordId中值inserted
  2. 停止为此使用存储过程并执行它在触发器内执行的任何逻辑,作为基于集合的操作。