Sometimes I have to delete two records on different tables. How could I execute the query in a way where if one fails the other one will not execute and the other way around. In other words, that the database gets updated only if both queries are successful otherwise don’t make any changes. That way if I get any errors I know nothing has changed. I am executing this query in C# as:
//qDelete is a string containing the query
// connection - SqlConnection
SqlCommand cmd = new SqlCommand(qDelete, connection);
try
{
var t = cmd.ExecuteNonQuery();
MessageBox.Show("Query succesfully executed \n \n" + "\n\n" + t + " records successfully deleted");
}
catch
{
//do something here to avoid having any changes to the database
}
That’s is great. My sDelete string gets build dynamically and the only things that I am missing is to place the statements in the right order. I have figured that I have to delete first the records from the dependent table or table that has constrains then from the other table. How could I see which table is dependent on the other will help me build this query. I could do something like sort all the strings and place the ones that contains the table that has no constrain first then place the other ones. How can I find out which table depends on the other to make this even better?
You want to use a Transaction to gather the two updates together and let them either both succeed or neither happen. That link includes a sample that does two inserts, but you can easily adapt it for two deletes.