Re: How to distinguish operation type in 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..

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

"Hubert Trzewik" <hubert.trzewik@xxxxxxxxx> wrote in message news:1180606751.757434.101410@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
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


.



Relevant Pages

  • Re: Can I Pass a Table Name as a Parameter?
    ... I'm not even sure a check constraint is the right way to go. ... Surely any rule you create writing a trigger can be replicated within a SP ... I have re-read his bit about "Common Cases when to Use Dynamic ... SELECT * FROM @tablename", ...
    (microsoft.public.sqlserver.programming)
  • Re: D.C. Police to Carry Semiautomatic Rifles on Patrols
    ... The most common changes are the NY trigger and the ... NY+ (about 12 -14 lbs) along with the connector. ... My triggers are much closer to a normal single action. ...
    (talk.politics.guns)
  • Re: Can I Pass a Table Name as a Parameter?
    ... if inserted and deleted were accesible to a UDF called from a trigger. ... I realised after I had posted that the dynamic-SQL ... I have re-read his bit about "Common Cases when to Use Dynamic SQL: ...
    (microsoft.public.sqlserver.programming)
  • Re: Can I Pass a Table Name as a Parameter?
    ... but my understanding is that it only contains inserted records. ... -Inserted refers to the table the trigger is created on. ... I have re-read his bit about "Common Cases when to Use Dynamic ...
    (microsoft.public.sqlserver.programming)
  • Re: D3 File Trigger not Writing to file
    ... I would write a trigger without constraints to see if the scenario you ... COMMON /CLOG/ FLAG, FILE.UPDATES.CLOG ... Triggers must be lean therefore you should use expensive statements ... Instead of having an OPEN on every log request I suggest you use a ...
    (comp.databases.pick)