且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在SQL Server中使用单个SQL查询删除多个表中的数据

更新时间:2023-01-23 10:42:07

由于删除语句只能在SQL中一次从一个表中删除,因此必须使用存储过程一次从多个表中删除。



但是,在表 tbl1 , Pname c> tbl2 , tbl3 tbl5 是 tbl4 。如果是这种情况,那么你想进行级联删除 - 这里有一篇关于CodeProject主题的文章带有示例的SQL Server中的CASCADE [ ^ ]

...以及来自不同来源的另一个使用外键的DELETE CASCADE选项 [ ^ ]
As a delete statement can only delete from one table at a time in SQL, you have to use a stored procedure to delete from multiple tables "at once".

However, it looks as if Pname in tables tbl1, tbl2, tbl3 and tbl5 are foreign keys to Pname on tbl4. If that is the case then you want to do a "cascade delete" - here is one article on the subject in CodeProject CASCADE in SQL Server with Example[^]
...and another from a different source Using DELETE CASCADE Option for Foreign Keys[^]




创建数据库存储过程并调用以下查询,当您从gridview中删除时,将id传递给存储过程

类似:

创建过程p_Delete_records

(id int)

as

开始

DECLARE @ID INT = 123;

从Tbl1删除,其中PName = @ ID;

从Tbl2删除,其中PName = @ID;

从Tbl3删除,其中PName = @ ID;

从Tbl5删除,其中PName = @ ID;

从Tbl4删除,其中ID = @ID ;

结束
Hi,
Create a Database store procedure and call the below query and when you are deleting from the gridview pass the id to store procdeure
Like:
Create Procedure p_Delete_records
(id int)
as
begin
DECLARE @ID INT =123;
DELETE from Tbl1 where PName=@ID;
DELETE from Tbl2 where PName=@ID;
DELETE from Tbl3 where PName=@ID;
DELETE from Tbl5 where PName=@ID;
DELETE from Tbl4 where ID=@ID;
end