Delete statement in SQL is very slow

前端 未结 15 685
自闭症患者
自闭症患者 2020-12-22 23:23

I have statements like this that are timing out:

DELETE FROM [table] WHERE [COL] IN ( \'1\', \'2\', \'6\', \'12\', \'24\', \'7\', \'3\', \'5\')
相关标签:
15条回答
  • 2020-12-22 23:54

    In my case the database statistics had become corrupt. The statement

    delete from tablename where col1 = 'v1' 
    

    was taking 30 seconds even though there were no matching records but

    delete from tablename where col1 = 'rubbish'
    

    ran instantly

    running

    update statistics tablename
    

    fixed the issue

    0 讨论(0)
  • 2020-12-22 23:54

    If you're deleting all the records in the table rather than a select few it may be much faster to just drop and recreate the table.

    0 讨论(0)
  • 2020-12-22 23:55

    I read this article it was really helpful for troubleshooting any kind of inconveniences

    https://support.microsoft.com/en-us/kb/224453

    this is a case of waitresource KEY: 16:72057595075231744 (ab74b4daaf17)

    -- First SQL Provider to find the SPID (Session ID)
    
    -- Second Identify problem, check Status, Open_tran, Lastwaittype, waittype, and waittime
    -- iMPORTANT Waitresource select * from sys.sysprocesses where spid = 57
    
    select * from sys.databases where database_id=16
    
    -- with Waitresource check this to obtain object id 
    select * from sys.partitions where hobt_id=72057595075231744
    
    select * from sys.objects where object_id=2105058535
    
    0 讨论(0)
  • 2020-12-22 23:56

    If the table you are deleting from has BEFORE/AFTER DELETE triggers, something in there could be causing your delay.

    Additionally, if you have foreign keys referencing that table, additional UPDATEs or DELETEs may be occurring.

    0 讨论(0)
  • 2020-12-23 00:00

    Check execution plan of this delete statement. Have a look if index seek is used. Also what is data type of col?

    If you are using wrong data type, change update statement (like from '1' to 1 or N'1').

    If index scan is used consider using some query hint..

    0 讨论(0)
  • 2020-12-23 00:01

    Deleting a lot of rows can be very slow. Try to delete a few at a time, like:

    delete top (10) YourTable where col in ('1','2','3','4')
    while @@rowcount > 0
        begin
        delete top (10) YourTable where col in ('1','2','3','4')
        end
    
    0 讨论(0)
提交回复
热议问题