有没有人对这两种方法中哪一种更适合大型删除有任何建议?

时间:2010-06-08 19:17:46

标签: sql query-optimization bulkinsert

方法#1:

DECLARE @count int
SET @count = 2000

DECLARE @rowcount int
SET @rowcount = @count

WHILE @rowcount = @count BEGIN

DELETE TOP (@count) FROM ProductOrderInfo
WHERE ProductId = @product_id 
AND bCopied = 1 AND FileNameCRC = @localNameCrc

SELECT @rowcount = @@ROWCOUNT

WAITFOR DELAY '000:00:00.400'

方法#2:

DECLARE @count int
SET @count = 2000

DECLARE @rowcount int
SET @rowcount = @count

WHILE @rowcount = @count BEGIN

DELETE FROM ProductOrderInfo
WHERE ProductId = @product_id AND FileNameCRC IN 
(
SELECT TOP(@count) FileNameCRC
FROM ProductOrderInfo WITH (NOLOCK)
WHERE bCopied = 1 AND FileNameCRC = @localNameCrc
)

SELECT @rowcount = @@ROWCOUNT

WAITFOR DELAY '000:00:00.400'

END

1 个答案:

答案 0 :(得分:1)

他们分开的东西,在最上面的一个你将你的删除限制为符合条件的2000行。然而,在底部,您将限制select返回2000行,尽管产品ID,然后仅删除ProductID = @product_id的那些行。底部的选择性更强,可以删除更少的行。

DELETE FROM ProductOrderInfo
WHERE ProductId = @product_id AND FileNameCRC IN 
(
  -- Now if @count is 2000
  -- You're guarentted *at most* 2000 rows
  -- *none* of which are guaranteed to have `ProductId = @product_id`

  SELECT TOP(@count) FileNameCRC
  FROM ProductOrderInfo WITH (NOLOCK)
  WHERE bCopied = 1 AND FileNameCRC = @localNameCrc
)