SQL deadlock on delete then bulk insert

﹥>﹥吖頭↗ 提交于 2019-12-04 09:06:51

Following on from Sam Saffron's answer:

  • Consider READPAST hint to skip over any held locks if @ID7@SubID is distinc
  • Consider SERIALIZABLE and remove XLOCK, HOLDLOCK
  • Use a separate staging table for the bulk insert, then copy from that

Its hard to give you an accurate answer without having a list of indexes / table size etc, however keep in mind that SQL can not grab multiple locks at the same instance. It will grab locks one at at time, and if another connection already holds the lock and it holds a lock to something the first transaction needs, kaboom you have a deadlock.

In this particular instance there are a few things you can do:

  1. Ensure there is an index on (Id, SubId), that way SQL will be able to grab a single range lock for the data being deleted.
  2. If deadlocks become rare, retry your deadlocks.
  3. You can approach this with a sledghammer and use a TABLOCKX which will not deadlock ever
  4. Get an accurate deadlock analysis using trace flag 1204 http://support.microsoft.com/kb/832524 (the more info you have about the actual deadlock the easier it is to work around)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!