Deadlock error on same table with two Update SQL statements

不问归期 提交于 2019-12-04 03:14:10

The question doesn't contain enough of the scenario for me to be able to replicate the example, so I'm going to speculate.

SqlCommand is disposable; but is not in a using block, and is not being disposed, so I would suspect that the previous command is still interfering with the database when the subsequent command takes place.

Put both SqlCommands into "using" blocks; and while you're at it, remove the "finally{connection.Close();}", and also put the SqlConnection into a "using" block as well (the Dispose will do the Close).

As would have determined by now, dead-locks are 'complex beasts' !

Theoretically, since you are updating a single table, there is no 2 tables involved to explain a 'classic dead-lock' scenario. So, you would expect to NOT get a dead-lock, BUT you are getting it ! Welcome to the real world :-)

Based on your deadlock trace xml, you seem to be getting dead-locks due to "Page Lock" i.e., SQL server is locking a page and your process is dead-locking on a Page (i.e., not just your record).

If you look at the resource-list section of your deadlock trace, you can see that your victim process is waiting for a page which is locked by another process.

One simple technique you can try is to use the ROWLOCK hint for your update statement and see if that helps in your scenario.

Related SO post: https://dba.stackexchange.com/questions/121610/how-to-force-sql-server-to-use-row-locking-for-specific-update-delete-statements

UPDATE Table1 WITH (ROWLOCK)
SET FirstName = 'first'
WHERE ID = 1

In the above example WITH (ROWLOCK) is your hint to SQL server to try to use row level locks

Also, some good reading about SQL server dead-locks is in this Simple Talk link

Depending on circumstances, MSSQL server locks whole pages (multiple rows) rather than single rows. This is why a deadlock can occour even if every client accesses only it's own rows. Also I have experienced fake-deadlocks that where really timeouts of a very busy server.

1) Tell SQL Server to use row locking (instead of page locking). This might be performance-expensive.

 UPDATE products WITH (ROWLOCK) SET ...

2) Make sure to use the primary key in your where condition.

Unrelated to your deadlock problem:

3) You have nested loops where you fire single statements to MSSQL. Reduce the number of queries by building up one or two big statements. This should boost your runtime performance

4) Dispose your SqlConnection and SqlCommand.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!