views:

62

answers:

1

Is there more recomended way of determining command type in the trigger then testing DELETED and INSERTED tables?

Currently i'm using approch:

(EXISTS (select 1 from INSERTED) AND NOT EXISTS (select 1 from DELETED)) = INSERT
(EXISTS (select 1 from INSERTED) AND EXISTS (select 1 from DELETED)) = UPDATE
(NOT EXISTS (select 1 from INSERTED) AND EXISTS (select 1 from DELETED)) = DELETE
+3  A: 

Quickest:

IF NOT EXISTS (SELECT * FROM DELETED)
   PRINT 'INSERT'
ELSE IF NOT EXISTS (SELECT * FROM INSERTED)
   PRINT 'DELETE'
ELSE
   PRINT 'UPDATE'

More Inefficient

SELECT @foo int
SET @foo = (SELECT COUNT(*) FROM INSERTED) - (SELECT COUNT(*) FROM DELETED)
IF @foo > 0
   PRINT 'INSERT'
ELSE @foo < 0
   PRINT 'DELETE'
ELSE
   PRINT 'UPDATE'

Generally, you'll rarely have a trigger that covers all 3. In my experience it's U/D or I/U where you can check less.

Note, the trigger on MyTable below still fires but no rows are actually inserted. You can not trap this unless you have a separate insert trigger

INSERT dbo.Mytable (col1,...)
SELECT
     value1, ...
WHERE
     1 = 0
gbn
"Generally, you'll rarely have a trigger that covers all 3." I agree, I almost never have a trigger that isn't only for one type of action.
HLGEM
Thanks for that, indeed your version is more optimized. In my scenario I need all commands to be covered as I designed and developed kind of user fiendly, trigger based yet efficient change data capture system for sql 2000 you can see it here http://vimeo.com/7320439.
Tomek
@Tomek: please accept the answer using the big tick on the left :-)
gbn