简体   繁体   English

SQL Server 2008 中的触发器

[英]Triggers in SQL Server 2008

I have created triggers for INSERT and UPDATE separately.我已经分别为 INSERT 和 UPDATE 创建了触发器。 The trigger is going to insert a row in Schema2 when an insert is made in Schema1.当在 Schema1 中进行插入时,触发器将在 Schema2 中插入一行。 Tables:表:

  • Schema1.Temp1 Schema1.Temp1
  • Schema2.Temp2 Schema2.Temp2

The trigger creation is successful.触发器创建成功。


But when I am inserting data in Temp1 , it is giving me error for Temp2 -- duplicate key.但是当我在Temp1中插入数据时,它给了我Temp2的错误——重复键。 Temp2 has constraints for two other tables. Temp2对另外两个表有约束。 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).当您的触发器被调用时,请尝试在 Table2 上写入(如您所说)。

Peraphs you haven't written INSERT query using a condition on existence of your Temp1 row in Temp2.您还没有使用 Temp2 中存在 Temp1 行的条件编写 INSERT 查询。

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.通过这种方式,您可以防止重复键,因此如果您也想在插入中更新您的 table2,您可以在该键已经存在时编写一个 UPDATE 语句。

Tell me if it's ok告诉我是否可以

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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