I want to write a stored procedure like the one below
allInterestingKeys = SELECT MyKey FROM MyTable WHERE CreatedDate < CAST('2013-01-01' AS date)
DELETE MyTable01 WHERE MyKey IN allInterestingKeys
DELETE MyTable02 WHERE MyKey IN allInterestingKeys
...
DELETE MyTable10 WHERE MyKey IN allInterestingKeys
Ideally I want to run SELECT MyKey FROM MyTable WHERE ... only once to make the procedure more efficient and readable than
DELETE MyTable01 WHERE MyKey IN (SELECT MyKey FROM MyTable WHERE CreatedDate < CAST('2013-01-01' AS date))
DELETE MyTable02 WHERE MyKey IN (SELECT MyKey FROM MyTable WHERE CreatedDate < CAST('2013-01-01' AS date))
...
DELETE MyTable10 WHERE MyKey IN (SELECT MyKey FROM MyTable WHERE CreatedDate < CAST('2013-01-01' AS date))
What is the best way to code it? Thanks.
Use a temp table!
SELECT INTOis the easiest, but you could also design the table ahead of time andINSERT INTOthe temp tableThen select the list from your temp table
Or
INNER JOINto the temp table to delete