HiveBrain v1.2.0
Get Started
← Back to all entries
snippetModerate

How to determine if insert or update

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
updateinsertdeterminehow

Problem

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.

Some one can please help me how to solve?

Code:

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

Solution

Since it's only UPDATE,INSERT you can say:

IF EXISTS (SELECT 1 FROM deleted)
  -- update
ELSE
  -- insert


You have a bigger problem, though. There is no such thing as new.Id, and an insert or update can affect multiple rows (in some platforms, triggers fire per row; in SQL Server, they fire per operation). So you need to either:

  • Use a loop to call the stored procedure for all of the RecordId values in inserted.



  • Stop using a stored procedure for this and perform whatever logic it does inside the trigger, as a set-based operation.

Code Snippets

IF EXISTS (SELECT 1 FROM deleted)
  -- update
ELSE
  -- insert

Context

StackExchange Database Administrators Q#77755, answer score: 10

Revisions (0)

No revisions yet.