简体   繁体   English

在SQL Server中触发之前

[英]Before trigger in SQL Server

I have 2 tables: survey (id(PK), name) and survey_to_topic (survey_id(PK,FK,not null), topic_id(PK,FK,not null)) . 我有2个表: survey_to_topic (survey_id(PK,FK,not null), topic_id(PK,FK,not null)) survey (id(PK), name)survey_to_topic (survey_id(PK,FK,not null), topic_id(PK,FK,not null)) When I try to delete from survey table, I get exception: 当我尝试从调查表中删除时,出现异常:

"The DELETE statement conflicted with the REFERENCE constraint "FK_survey _to _topic _survey". The conflict occurred in database "mydatabase", table "dbo.survey _to _topic", column 'survey _id'." “ DELETE语句与REFERENCE约束“ FK_survey _to _topic _survey”发生冲突。该冲突发生在数据库“ mydatabase”的表“ dbo.survey _to _topic”的“ survey _id”列中。”

So to get no error first I must delete record from table survey_to_topic and after that from table survey. 因此,为了没有错误,我必须先从表survey_to_topic中删除记录,然后再从表Survey中删除记录。 I think it is better to do with before trigger on table survey, but I can't find any information about this. 我认为最好在进行表格调查之前先进行触发,但是我找不到任何有关此的信息。 There are a lot of articles about before triggers in PL/SQL, but I use SQL Server. 关于PL / SQL中的触发器之前的文章很多,但是我使用SQL Server。

You can add ON DELETE CASCADE to the relationship between the two tables, and the records from the survey_to_topic table will be deleted automatically. 您可以将ON DELETE CASCADE添加到两个表之间的关系中,Survey_to_topic表中的记录将被自动删除。

See http://msdn.microsoft.com/en-us/library/aa933119(SQL.80).aspx 请参阅http://msdn.microsoft.com/zh-cn/library/aa933119(SQL.80).aspx

You can use ON DELETE CASCADE. 您可以使用ON DELETE CASCADE。 This is added to the table containing the FK. 这将添加到包含FK的表中。

See example here . 在这里查看示例。

As Alex Deem and astander already mentioned - you should use ON DELETE CASCADE on your foreign key relationship - that handles this scenario automatically for you. 正如Alex Deem和旁观者已经提到的那样-您应该在外键关系上使用ON DELETE CASCADE-这样可以自动为您处理这种情况。

SQL Server doesn't know the concept of BEFORE (operation) TRIGGERs - SQL Server has AFTER triggers, or then INSTEAD OF triggers. SQL Server不知道“触发(操作)”触发器之前的概念-SQL Server具有AFTER触发器,然后是INSTEAD OF触发器。 See the Introduction to triggers article for some background info. 有关一些背景信息,请参见“ 触发器简介”文章。

But ON DELETE CASCADE is definitely the easiest way to do this. 但是ON DELETE CASCADE绝对是执行此操作的最简单方法。

As everyone else here mentioned, ON DELETE CASCADE is a way to go -- as long as you are aware of consequences; 正如这里的其他人所提到的,只要您知道后果,“ ON DELETE CASCADE就是一个ON DELETE CASCADE的方法。 there is a reason why ON DELETE NO ACTION (raise error) is the default. 这是默认情况下“不ON DELETE NO ACTION (引发错误)的原因。 In other words, you should plan your deletion strategy -- it is too easy to wipe out rows from several tables unintentionally by using ON DELETE CASCADE . 换句话说,您应该计划删除策略-通过使用ON DELETE CASCADE意外擦除多个表中的行太容易了。

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

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