Why does SQL Update Top seem to reduce locks even when no records are updated?

My question is why some kind of SQL (running on SQL Server 2005) behaves as it is. In particular, I made changes to reduce the lock conflict during the update, and it seems to work in cases where I did not think it would be.

Source:

We had an update statement that applied to a table with more than 3,000,000 records:

UPDATE  USER WITH (ROWLOCK)
SET Foo = 'N', Bar = getDate()
WHERE ISNULL(email, '') = ''
AND   Foo = 'Y'

As you probably guessed, this caused the USER table to be delayed for a while. Even with the ROWLOCK prompt, other jobs that perform queries and updates against USER are blocked until this is completed. This is not acceptable for this particular application, so I thought I would apply the trick I was reading about if the update instruction updates only 100 records at a time. This would give other requests the opportunity to periodically appear at the table.

Improved code:

DECLARE @LOOPAGAIN AS BIT;
SET @LOOPAGAIN = 1;

WHILE @LOOPAGAIN = 1
  BEGIN
    UPDATE TOP (100) USER WITH (ROWLOCK)
    SET Foo = 'N', Bar = getDate()
    WHERE ISNULL(email, '') = ''
    AND   Foo = 'Y'

    IF @@ROWCOUNT > 0
      SET @LOOPAGAIN = 1
    ELSE
      SET @LOOPAGAIN = 0
  END

It did the trick. Our update did its job, and other requests were received at the table. All this is happiness and light.

Secret:

, , . 100 , . , , !

, , (, 30 ), , . "TOP (100)", , , !

. - :

  • , , ,
  • ?
+3
4

.

, , 3000 000 . , :

, , , , , User. , , .

:

  • ( !).
  • .
  • 1211 ( !).

. , SQL Server.

, , SQL Server Profiler Lock: Escalation.

+3
  • .
  • ISNULL(email, '') = '' AND Foo = 'Y'.

, , , .

, Email Foo ( , ).

, ? ?

0

, SQL Server TOP 200, ROWLOCK. - Management -> Activity Montior, Locks by Object?

0

, , :

Foo = 'N', Bar = getDate() FROM (SELECT USER.ID FROM USER// NOLOCK , , uncommitted. WHERE COALESCE (EMAIL, '') = '' AND Foo = 'Y') D WHERE D.ID = USER.ID

0

Source: https://habr.com/ru/post/1722500/


All Articles