When I execute the following SQL in the management studio the query returns the expected result:
SELECT MAX(ID) FROM table WHERE field = value;
However when my client application (WinForms) execute’s this SQL in the middle of a Transaction the query Times Out without returning a value. I suspect this is because the Transaction includes other SQL statements which are adding to / amending the same ‘table’.
How do I work around this?
“SELECT MAX(ID)” is an aggregate function and will do a lot of locking on the table – a shared read lock can potentially be taken on all the records in the table, certainly on all those that match your criteria, and others depending on whether row or page locks are used. If there is an outstanding write lock on any of these records that the MAX wants to lock, then the MAX will time out. You need to understand what other locks are in place at the same time. If you are using SQL Server, then you can use SQL Profiler to get a trace which will show you all the locks on that table, including locks from other transactions.