简体   繁体   中英

Replace subquery with variable SQL Server

I have multiple delete statements to run on 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')

Is there a way that I can use a variable to replace the repetitive subquery? Is there such a variable type to hold the subquery or its results?

Thank you

Table variable to hold the IDs to delete...

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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