如何判断是插入还是更新

2022-01-01 00:00:00 sql-server triggers

每当在 CUSTOMER 表中发生 INSERT 时,我都需要调用StoredProcedure1"和更新发生在 CUSTOMER 表中,我需要在触发器中调用StoredProcedure2".如何确定在触发器中插入还是更新来自 SQL Server 2008.

Whenever INSERT is happened in the CUSTOMER table,I need to call the "StoredProcedure1"and UPDATE is happend in the CUSTOMER table,I need to call the "StoredProcedure2" in the Trigger. How to determine if insert or update in the trigger from 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

推荐答案

试试这个代码,用于 INSERT、UPDATE 和 DELETE 的触发器.这在 Microsoft SQL SERVER 2008 上运行良好

Try this code for trigger for INSERT, UPDATE and DELETE. This works fine on Microsoft SQL SERVER 2008

if (Select Count(*) From inserted) > 0 and (Select Count(*) From deleted) = 0
begin
   print ('Insert...')
end

if (Select Count(*) From inserted) = 0 and (Select Count(*) From deleted) > 0
begin
   print ('Delete...')
end

if (Select Count(*) From inserted) > 0 and (Select Count(*) From deleted) > 0
begin
   print ('Update...')
end

相关文章