Groups | Blog | Home
all groups > sql server (alternate) > may 2007 >

sql server (alternate) : How to distinguish operation type in trigger?


Hubert Trzewik
5/31/2007 3:19:11 AM
Hi,

I want to have all-in-one trigger, defined like this:

CREATE TRIGGER MyInsertDeleteUpdateHandler
ON MyTable
FOR DELETE, INSERT, UPDATE
AS
BEGIN
(...)
END

Now, how can I tell why this trigger was fired (what event caused
trigger to be fired) - was it DELETE, INSERT or UPDATE?

Is there something like this: @@event_type,
so I could do for example IF (@@event_type = DELETE) (...)

Of course I can create 3 triggers instead of 1, to be sure what event
fired my trigger.

I can also count records in _deleted_, _inserted_ tables or to do
JOINs with it. But, _inserted_ table is common for UPDATE and INSERT
events..

Any suggestions?
Thanks in advance.

Hubert
M A Srinivas
5/31/2007 4:48:38 AM
[quoted text, click to view]

For Inserted : Rows are in inserted only
For Updated: Rows are in inserted and deleted
For deleted: Rows are in deleted only
Hubert Trzewik
5/31/2007 6:32:09 AM
[quoted text, click to view]

That's right. One test more and.. UPDATE is seen both in _inserted_
and _deleted_, so I can distinguish it from INSERT (and DELETE of
course).

Thanks a lot.

Hubert
Dan Guzman
5/31/2007 11:43:43 AM
[quoted text, click to view]

However, the deleted table will be empty for when fired by INSERT. You can
determine the statement type as follows:

IF EXISTS(SELECT * FROM inserted)
IF EXISTS(SELECT * FROM deleted)
SELECT @event_type = 'update'
ELSE
SELECT @event_type = 'insert'
ELSE
IF EXISTS(SELECT * FROM deleted)
SELECT @event_type = 'delete'
ELSE
--no rows affected - cannot determine event
SELECT @event_type = 'unknown'

--
Hope this helps.

Dan Guzman
SQL Server MVP

[quoted text, click to view]
Seribus Dragon
6/4/2007 1:48:25 PM
Why not just break up the action into three triggers? if there is
common code use a stored procedure got that part.

[quoted text, click to view]
Erland Sommarskog
6/4/2007 9:15:44 PM
Seribus Dragon (Seribus.news@seribus.com) writes:
[quoted text, click to view]

That can be problematic, if you need to refer to the inserted/deleted
tables, which you often do in triggers.

Most of my triggers are for INSERT and UPDATE, but I have a couple
that are for all three actions.

--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
AddThis Social Bookmark Button