Here is my requirement:
- I want to delete multiple rows of a table
- I have the list of all ids that needs to be deleted in the client app.
- All I want is to make just a single call from my C# client app to delete all these records.
What I had earlier:
foreach (var id in idList)
{
//Call a Stored Procedure which takes the id
//as parameter and deletes the record
}
This is a problem because there is a database hit for each item in loop.
Then I started using the SQL Server 2008 newly introduced Table Types and Table Valued Parameters for stored procedures for this.
- First have a Table Type created in the database which has a single column (of type of Id)
- Create a new Stored Procedure which accepts this new table type (Table Valued Parameter)
- In the Client code, create a list/Datatable with all the ids to be deleted.
- Make a single call to the database to make use of the new stored Procedure.
It is pretty straight forward in the client code, which goes something like this:
SqlParameter parameter = new SqlParameter();
parameter.SqlDbType = System.Data.SqlDbType.Structured;
OK - Though I achieved what I set for, this definitely does not work for SQL server versions before 2008.
So what I did was to introduce a fall back mechanism:
- I introduced a Stored Procedure that takes comma separated id values
- My client code will create such comma separated ids, and then simply pass it to the new stored proc.
- The Stored Proc will then split all those ids, and then call delete one by one.
- So in a way, I have achieved what I had set for even on SQL Server version prior to 2008: delete multiple rows with a single database hit.
But I am not that convinced with the last approach I took - A quick search on the internet did not reveal anything much.
So can somebody tell me if I am doing the right thing with comma separated ids and all.
What is the usual best practice to delete multiple records from the client app with a single database hit, provided the ids are known.
Thanks in advance.