2

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

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

谢谢

4

1 回答 1

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)
于 2015-08-18T04:16:50.123 回答