如何使用 instead of delete 触发器并仍然删除 SQL 服务器中的行
How to use instead of delete trigger and still delete the row in SQL Server
我想从我的数据库中的 table 中删除一行,但首先我必须通过外键删除与该行对应的行。
我在主 table 及其内部使用 instead of
触发器,我首先从与该主行对应的其他 table 中删除子行,然后然后我想删除主行。但是(正如预期的那样)主行没有被删除,因为它是一个 INSTEAD OF
触发器。
如果我尝试删除而不是触发器中的主行,我会收到错误消息:
INSTEAD OF triggers do not support direct recursion. The trigger execution failed
如果我尝试使用 AFTER DELETE
触发器,我会收到错误消息:
The DELETE statement conflicted with the REFERENCE constraint [...]
因为我正试图删除与其他 table 中的其他行相对应的行。
我一直在想办法解决这个问题,但我卡住了,在 Internet 上找不到可行的解决方案。我觉得我遗漏了一些明显的东西,但我似乎找不到它。
谢谢大家保重!
问题已在@ZLK 的帮助下使用级联删除解决或:
@ZLK: You also have the option of altering the table to not check the constraint. For example, alter table X nocheck constraint myConstraintName
, then doing the delete statement / data manipulation (e.g. in an after delete trigger) then turning the constraint back on alter table X check constraint myConstraintName
我想从我的数据库中的 table 中删除一行,但首先我必须通过外键删除与该行对应的行。
我在主 table 及其内部使用 instead of
触发器,我首先从与该主行对应的其他 table 中删除子行,然后然后我想删除主行。但是(正如预期的那样)主行没有被删除,因为它是一个 INSTEAD OF
触发器。
如果我尝试删除而不是触发器中的主行,我会收到错误消息:
INSTEAD OF triggers do not support direct recursion. The trigger execution failed
如果我尝试使用 AFTER DELETE
触发器,我会收到错误消息:
The DELETE statement conflicted with the REFERENCE constraint [...]
因为我正试图删除与其他 table 中的其他行相对应的行。
我一直在想办法解决这个问题,但我卡住了,在 Internet 上找不到可行的解决方案。我觉得我遗漏了一些明显的东西,但我似乎找不到它。
谢谢大家保重!
问题已在@ZLK 的帮助下使用级联删除解决或:
@ZLK: You also have the option of altering the table to not check the constraint. For example,
alter table X nocheck constraint myConstraintName
, then doing the delete statement / data manipulation (e.g. in an after delete trigger) then turning the constraint back onalter table X check constraint myConstraintName