The question involves SQL Server and C#.
I am trying to execute multiple delete statements in one query. The format has the following structure:
DELETE from dbo.table where column = 'value'
repeated more than 100000 times
I build the command through a StringBuilder
and call it that way in my C# code:
cmd.Connection = con;
int rows = cmd.ExecuteNonQuery();
However it takes a lot of time to execute and ends with this error:
The timeout period elapsed prior to completion of the operation or the server. Executing through Management Studio takes also a lot of time, and let me think that the query isn't performant enough. However, in this case the query is executed successfully.
Obviously, using fewer DELETE
statements, the query ends properly due it's a very simple query. What is the best way to execute multiple statements and avoid this error?
DELETE
statement. However, if you pass 5'000 rows in a single transaction, SQL Server will do a lock escalation and move the lock to the entire table which becomes exclusively locked until the transaction finishes. This means: until the transaction finishes, no one can even read from that table! So maybe you need to batch up yourDELETE
operations into smaller batches to avoid an exclusive table lock – marc_s