用可变SQL Server替换子查询

时间:2015-08-18 04:02:27

标签: sql variables sql-server-2008-r2 subquery smss

我有多个要在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')

有没有办法可以使用变量来替换重复的子查询?是否有这样的变量类型来保存子查询或其结果?

谢谢

1 个答案:

答案 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)