我有多个要在SQL Server 2008 R2上运行的删除语句
DELETE FROM A WHERE A_id in (SELECT B_id FROM B WHERE B_name = 'Target')
DELETE FROM B WHERE B_id in (SELECT B_id FROM B WHERE B_name = 'Target')
DELETE FROM C WHERE C_id in (SELECT B_id FROM B WHERE B_name = 'Target')
DELETE FROM D WHERE D_id in (SELECT B_id FROM B WHERE B_name = 'Target')
有没有办法可以使用变量来替换重复的子查询?是否有这样的变量类型来保存子查询或其结果?
谢谢
答案 0 :(得分:0)
用于保存要删除的ID的表变量...
Declare @BIDs Table
(
B_Id Int Not Null
)
Insert Into @BIDs (B_Id)
SELECT B_Id FROM B WHERE B_Name = 'Target'
DELETE FROM A WHERE A_id in (SELECT B_id FROM @BIDs)
DELETE FROM B WHERE B_id in (SELECT B_id FROM @BIDs)
DELETE FROM C WHERE C_id in (SELECT B_id FROM @BIDs)
DELETE FROM D WHERE D_id in (SELECT B_id FROM @BIDs)