sql server中ON DELETE CASCADE的删除触发器问题
我在 Sql 服务器中有两个表
Table A: Id UNIQUEIDENTIFIER NOT NULL
Table B: Id UNIQUEIDENTIFIER NOT NULL
AId UNIQUEIDENTIFIER NOT NULL,ON DELETE CASCADE (This is Id of Table A)
(注意 B 的 AId 列使用 ON DELETE CASCADE 选项引用 A)。 B 也有一个删除触发器,就像
CREATETRIGGER B_Delete_Trigger
ON [dbo].[B]
FOR DELETE
AS
SELECT * FROM DELETED AS B INNER JOIN A ON B.AId=A.Id
现在当我对表 B 执行删除操作时,上面的触发器返回行,但是当打开时 表 A 没有返回任何内容。
据我所知,SQL Server 首先从子表(本例中为 B)删除记录,然后从父表(本例中为 A)删除记录,因此上面的触发器应该在这两种情况下返回一些记录。
请告诉我如何访问父母记录,否则我的观察是错误的。
I have two Tables in Sql server
Table A: Id UNIQUEIDENTIFIER NOT NULL
Table B: Id UNIQUEIDENTIFIER NOT NULL
AId UNIQUEIDENTIFIER NOT NULL,ON DELETE CASCADE (This is Id of Table A)
(Notice B has column AId that references A with ON DELETE CASCADE option).
B also has a delete trigger like
CREATETRIGGER B_Delete_Trigger
ON [dbo].[B]
FOR DELETE
AS
SELECT * FROM DELETED AS B INNER JOIN A ON B.AId=A.Id
Now when I perform delete operation on Table B, above trigger returns rows, but when on
Table A nothing is returned.
As much I know SQL Server first delete records from Child Table(B in this case) and then from parent(A in this case), so above trigger should return some record in both cases.
Please, tell me how to access parents records, Or my observation is wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
需要注意以下事项:
触发器
以执行ON DELETE CASCADE
ON DELETE CASCADE
表示:当您从父表中删除项目时,所有已删除引用的项目都将从子表中删除。希望你能接受我,谢谢你的时间。
Below items should be noted:
trigger
on parent table to performON DELETE CASCADE
ON DELETE CASCADE
means: when you delete item from Parent table, all items will be deleted from child table with deleted reference.Hope you've got me, thanks for your time.
实际上当你在表A上调用这个触发器时,执行顺序是
并且SELECT * FROM DELETED仅包含A表中的数据。
Actually when you call this trigger on table A. The execution sequence is
And SELECT * FROM DELETED contains only data from A table.
“FOR”触发器相当于“AFTER”触发器。触发器在删除操作完成后触发。因此,当B执行删除触发器时,表A中的记录已经消失了。据我所知,没有简单的方法可以访问表A中的记录。
A "FOR" trigger is equivalent to an "AFTER" trigger. The trigger fires after the delete operation has completed. Therefore, by the time the delete trigger executes for B, the record in table A is already gone. As far as I know, there is no simple way to get access to the record in table A.
删除级联不应该在父表上吗?
这样做的目的是,一旦父表被删除,当然前提是还有其他表引用父表(通过 FK 约束),那么所有子记录也将被删除。看来你搞错了??
MSDN:
http://msdn.microsoft.com/ en-us/library/aa933119(v=sql.80).aspx
Shouldn't the on delete cascade be on the parent table?
The purpose of this is that once the parent is deleted, providing there are other tables referencing the parent of course (via FK constraints), then all the child records will be deleted too. It looks like you have it the wrong way round??
MSDN:
http://msdn.microsoft.com/en-us/library/aa933119(v=sql.80).aspx