How to prevent lock on table when delete from table only ?

ahmed salah 3,216 Reputation points
2022-07-03T22:49:26.71+00:00

I work on sql server 2019 i face issue i can't prevent only lock when delete

first session is

select * from students where studentid between 10 and 50

second session is

update students set className='FirstClass' where studentid between 10 and 50

third session is

delete from students where studentid between 10 and 50

so i need to prevent lock on third session when make delete only

so i need to prevent delete when make delete only

so what i do to make that

Developer technologies Transact-SQL
SQL Server Other
{count} votes

3 answers

Sort by: Most helpful
  1. LiHong-MSFT 10,056 Reputation points
    2022-07-04T02:41:18.46+00:00

    Hi @ahmed salah
    See this sample:

    DELETE FROM LogMessages WHERE LogDate < '20020102';  
    

    Change to this:

    DECLARE @done bit = 0;  
    WHILE (@done = 0)  
    BEGIN  
        DELETE TOP(1000) FROM LogMessages WHERE LogDate < '20020102';  
        IF @@rowcount < 1000 SET @done = 1;  
    END;  
    

    Refer to this doc for more details: Resolve blocking problems caused by lock escalation in SQL Server

    Best regards,
    LiHong

    1 person found this answer helpful.
    0 comments No comments

  2. Olaf Helper 47,436 Reputation points
    2022-07-04T07:24:11.277+00:00

    so i need to prevent lock on third session when make delete only

    You can't; that's the way databases works to ensure ACID concept.
    https://en.wikipedia.org/wiki/ACID

    1 person found this answer helpful.
    0 comments No comments

  3. Tom Phillips 17,771 Reputation points
    2022-07-05T12:50:55.143+00:00

    As Olaf said, you cannot prevent locks. Locks are normal and expected in a multiuser database system.

    You have 2 queries trying to affect the same range of records. The server must wait do them one at a time and prevent the 2nd from happening until it is complete.

    What exactly is your issue?

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.