Sunday, March 25, 2012

Determine if a trigger exists.

I need to know how to determine if a specific trigger exists a on table and
if it does not i need to create it. Is this possible?
ThanksHi,
You may be able to use the following statement, but check the BOL
documentation for OBJECT_ID() because I'm not totally sure. Perhaps once
you've checked it out (or tested it) you can let the rest of us know how you
got along?
IF OBJECT_ID('dbname.owner.triggername') IS NULL
CREATE TRIGGER ...
Cheers,
Robert
"CSHARPITPRO" <CSHARPITPRO@.discussions.microsoft.com> wrote in message
news:684C9984-6AB3-41B2-8752-CB45BD8F00E5@.microsoft.com...
>I need to know how to determine if a specific trigger exists a on table and
> if it does not i need to create it. Is this possible?
> Thanks|||Hi, Robert
CREATE TRIGGER must be the first statement in a batch, so using it in
an IF statement won't work. There are (at least) two ways of dealing
with this:
a) drop the trigger if it exists and then create it:
IF OBJECT_ID('triggername') IS NOT NULL
DROP TRIGGER triggername
GO
CREATE TRIGGER ...
b) create the trigger if it doesn't exists, using EXEC('...'):
IF OBJECT_ID('triggername') IS NULL
EXEC('CREATE TRIGGER ...')
I preffer the first way, because:
1. By re-creating the trigger, I am sure that I have the correct
version of the trigger.
2. Using EXEC with a string means that I have to replace any
apostrophes in the trigger definition with double apostrophes.
Razvan|||Thanks for the help, I will try this today.
Thanks again!
"Razvan Socol" wrote:

> Hi, Robert
> CREATE TRIGGER must be the first statement in a batch, so using it in
> an IF statement won't work. There are (at least) two ways of dealing
> with this:
> a) drop the trigger if it exists and then create it:
> IF OBJECT_ID('triggername') IS NOT NULL
> DROP TRIGGER triggername
> GO
> CREATE TRIGGER ...
> b) create the trigger if it doesn't exists, using EXEC('...'):
> IF OBJECT_ID('triggername') IS NULL
> EXEC('CREATE TRIGGER ...')
> I preffer the first way, because:
> 1. By re-creating the trigger, I am sure that I have the correct
> version of the trigger.
> 2. Using EXEC with a string means that I have to replace any
> apostrophes in the trigger definition with double apostrophes.
> Razvan
>

No comments:

Post a Comment