简体   繁体   中英

Triggers in SQL Server 2008

I have created triggers for INSERT and UPDATE separately. The trigger is going to insert a row in Schema2 when an insert is made in Schema1. Tables:

  • Schema1.Temp1
  • Schema2.Temp2

The trigger creation is successful.


But when I am inserting data in Temp1 , it is giving me error for Temp2 -- duplicate key. Temp2 has constraints for two other tables. What can be causing this, and how can it be resolved?

When your trigger is called try to write on Table2 (as you've told).

Peraphs you haven't written INSERT query using a condition on existence of your Temp1 row in Temp2.

Your query must be of this type:

INSERT INTO Table2 (field list)
SELECT field list
FROM inserted
WHERE NOT EXISTS(SELECT 'key' in Table2 t2 where t2.id = inserted.field_of_key)

In this way you prevent duplicate key, so if you want to update your table2 in insert too, you can write an UPDATE stament when that key is already existing.

Tell me if it's ok

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM