How to prevent SQL update trigger from firing on insert?

5 pts.
Tags:
SQL Server
SQL Server 2005
T/SQL
Triggers
Category: SQL Server 2005, T-SQL I have an insert trigger on TableA that updates Column1 in TableA. I also have an update trigger on TableA that I don't want to fire, or at least not to execute certain code, when a new record is inserted in the table. How can this be achieved? I don't want to use a computed column instead of the update statement in the insert trigger -- the value has to be static, and I don't want performance hit when selecting from the table. Thanks, Leo

Answer Wiki

Thanks. We'll let you know when a new response is added.

You can merge both triggers into one trigger for update and insert:
<pre>
CREATE TRIGGER <trigger name> ON TableA for INSERT,UPDATE</pre>

If you have different logic for update and for insert, you can check Inside the trigger which command fired it. There are two ways to do so:
1) If you have a column that is always updated, you can ask:
<pre>IF UPDATE (column)</pre>
2) You can check if the deleted table is not empty, which means this is an update:
<pre>IF EXISTS (SELECT 1 FROM deleted</pre>

This way the trigger will not fire the second time, just make sure that the ‘recursive triggers’ db option is OFF:
<pre>exec sp_dboption <you database name>,’recursive triggers’</pre>

Hope this helps,
Michelle.

Discuss This Question: 1  Reply

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
  • dinuas400
    better you can combine both the logic into a single trigger program...
    510 pointsBadges:
    report

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

To follow this tag...

There was an error processing your information. Please try again later.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Thanks! We'll email you when relevant content is added and updated.

Following