CodexBloom - Programming Q&A Platform

best practices for deadlocks when using T-SQL transactions with multiple updates?

👀 Views: 96 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
sql-server t-sql deadlocks transactions T-SQL

I tried several approaches but none seem to work. I've spent hours debugging this and I'm writing unit tests and I'm relatively new to this, so bear with me. I'm working with deadlocks in my T-SQL code when performing updates on multiple tables within a transaction. I'm using SQL Server 2019 and while trying to update records in both the `Orders` and `Inventory` tables, I receive the behavior message: ``` Transaction (Process ID 123) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction. ``` Here's a simplified version of the code that's causing the scenario: ```sql BEGIN TRANSACTION; UPDATE Orders SET Status = 'Shipped' WHERE OrderID = 1001; UPDATE Inventory SET Quantity = Quantity - 1 WHERE ProductID = (SELECT ProductID FROM Orders WHERE OrderID = 1001); COMMIT TRANSACTION; ``` I've tried using `WITH (UPDLOCK)` in my SELECT statement to prevent other transactions from locking the `Inventory` table, but it hasn't resolved the deadlocks. I've also checked for any long-running transactions and they seem to be under control. Is there a best practice or a specific pattern I should follow to minimize the risk of deadlocks in this scenario? Would restructuring the order of the updates or using different isolation levels help in this case? Any ideas what could be causing this? This issue appeared after updating to T-Sql stable. What would be the recommended way to handle this? I'm working on a mobile app that needs to handle this. Any ideas what could be causing this?