Sunday, September 12, 2010

Update statement to update multiple SQL tables simultaneously ( c# windows form)

There are two ways to handle this :

Method 1

  1. SqlConnection conn = new SqlConnection("connection string goes here");
  2. try
  3. {
  4. SqlCommand cmd = new SqlCommand();
  5. cmd.Connection = conn;
  6. // write your condition here instead of true
  7. if (true)
  8. {
  9. // you can also execute multiple commands here instead of one
  10. // SQL Server allows multiple statements whereas Oracle does not
  11. // Or write a procedure to do this
  12. cmd.CommandText = @"UPDATE YourTable1 SET SomeColumn=@param1;
  13. UPDATE YourTable2 SET SomeColumn=@param2;";
  14. cmd.Parameters.AddRange(new SqlParameter[]
  15. {
  16. new SqlParameter()
  17. {
  18. ParameterName = "@param1",
  19. Value = "your value",
  20. DbType = DbType.String
  21. },
  22. new SqlParameter()
  23. {
  24. ParameterName = "@param2",
  25. Value = "your value",
  26. DbType = DbType.String
  27. }
  28. });
  29. conn.Open();
  30. cmd.ExecuteNonQuery();
  31. }
  32. }
  33. catch
  34. {
  35. // Handle exception here
  36. }
  37. finally
  38. {
  39. if (conn.State == ConnectionState.Open)
  40. conn.Close();
  41. conn.Dispose();
  42. }

Method 2

  1. SqlConnection conn = new SqlConnection("your conn string here");
  2. SqlTransaction trans;
  3. SqlCommand cmd1 = new SqlCommand("UPDATE Table1 SET Column1=Value1",conn,trans);
  4. SqlCommand cmd2 = new SqlCommand("UPDATE Table2 SET Column2=Value2",conn,trans);
  5. if(condition1)
  6. {
  7. conn.Open();
  8. trans = conn.BeginTransaction();
  9. try
  10. {
  11. cmd1.ExecuteNonQuery();
  12. cmd2.ExecuteNonQuery();
  13. trans.Commit();
  14. conn.Close();
  15. }
  16. catch(Exception ex)
  17. {
  18. trans.Rollback();
  19. }
  20. finally
  21. {
  22. if(conn.State == ConnectionState.Open)
  23. {
  24. conn.Close();
  25. }
  26. }
  27. }
  28. else
  29. {
  30. //do something else
  31. }

1 comment: