views:

50

answers:

1

Approach #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'

Approach #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  A: 

They do separate things, in the top one you're limiting your delete to 2000 rows that match the criteria. In the bottom one however, you're limiting a select to return 2000 rows, despite product id, and then deleting only the ones where ProductID = @product_id. The bottom one has more-selectivity and the potential to delete fewer rows.

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
)
Evan Carroll
What if I had AND ProductId = @product_id in the inner select?
RPS
Then the query would at least be correct, but what would it be achieving? The way MVCC works, `DELETES` acquire row-locks not table locks. In the top you're acquiring an exclusive row lock for the rows that pass the conditionals, in the bottom you're getting some sort of SHARED lock on all rows in the correlated sub-query that are being elevated by their encapsulating transaction. That's what I would expect anyway, but the sure answer is don't worry about it go with the top and let the db handle it.
Evan Carroll
Thanks for your input!
RPS