Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make changes to database only if all queries execute successfully

Tags:

c#

sql-server

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?

like image 487
Tono Nam Avatar asked Mar 02 '26 05:03

Tono Nam


2 Answers

The answer is to use a Transaction. Using the SqlConnection, begin a Transaction using the BeginTransaction() method; it will return a SqlTransaction. Then, there is an overload of the SqlCommand constructor that will take the transaction as well as the connection. Run the command(s), and at the end of the try block, call the Commit() method on the transaction. If you catch an error, call Rollback() on the transaction.

like image 142
KeithS Avatar answered Mar 04 '26 17:03

KeithS


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.

like image 23
Kate Gregory Avatar answered Mar 04 '26 18:03

Kate Gregory



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!