1

我想写一个像下面这样的存储过程

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 

理想情况下,我只想运行SELECT MyKey FROM MyTable WHERE ...一次以使程序比

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

最好的编码方式是什么?谢谢。

4

1 回答 1

2

使用临时表!SELECT INTO是最简单的,但您也可以提前设计表和INSERT INTO临时表

SELECT MyKey 
INTO #allInterestingKeys
FROM MyTable 
WHERE CreatedDate < CAST('2013-01-01' AS date)

然后从临时表中选择列表

DELETE MyTable01 WHERE MyKey IN (SELECT MyKey FROM #allInterestingKeys)

或者INNER JOIN到临时表中删除

DELETE t
FROM MyTable01 t
INNER JOIN #allInterestingKeys k
  ON t.MyKey = k.MyKey
于 2013-01-29T16:38:13.167 回答