简体   繁体   English

使用级联删除约束时获取已删除记录的计数

[英]Get the count for deleted records when using cascade delete constraint

When using ON DELETE CASCADE constraint and deleting a "master" record is there a way to get the count of "child" records deleted?当使用 ON DELETE CASCADE 约束并删除“主”记录时,有没有办法删除“子”记录的数量?

For example using these table:例如使用这些表:

CREATE TABLE Master ( ID INT PRIMARY KEY (ID))
GO

CREATE TABLE Child ( ID INT, MasterID INT)
GO

ALTER TABLE Child ADD CONSTRAINT FK_Child_Master FOREIGN KEY(MasterID)
REFERENCES Master (ID)
ON DELETE CASCADE
GO

INSERT INTO Master (ID) VALUES (1);

INSERT INTO Child ( ID, MasterID) VALUES (1,1),(2,1),(3,1),(4,1),(5,1);

Now if I delete the master record like this:现在,如果我像这样删除主记录:

DELETE FROM Master WHERE ID = 1;

SELECT @@ROWCOUNT;

The 5 rows in the Child table and the 1 row in the Master table are all deleted but the result is 1. It only counts the records deleted from the master table. Child表中的5行和Master表中的1行都被删除了,但结果是1。它只计算从主表中删除的记录。

Is there a way to capture the number of rows deleted from the child table or do I need delete from the child table first, get the count, then delete from the master?有没有办法捕获从子表中删除的行数,还是我需要先从子表中删除,获取计数,然后从主表中删除?

Yes you can use a stored procedure to do this like是的,您可以使用存储过程来执行此操作

create procedure spDeleteRecords
@id int
begin
    select count(*) from child_table where id=@id
    delete from parent_table where id=@id
end

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

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