There are two ways to handle this :
Method 1
- SqlConnection conn = new SqlConnection("connection string goes here");
- try
- {
- SqlCommand cmd = new SqlCommand();
- cmd.Connection = conn;
-
- if (true)
- {
-
-
-
- cmd.CommandText = @"UPDATE YourTable1 SET SomeColumn=@param1;
- UPDATE YourTable2 SET SomeColumn=@param2;";
- cmd.Parameters.AddRange(new SqlParameter[]
- {
- new SqlParameter()
- {
- ParameterName = "@param1",
- Value = "your value",
- DbType = DbType.String
- },
- new SqlParameter()
- {
- ParameterName = "@param2",
- Value = "your value",
- DbType = DbType.String
- }
- });
- conn.Open();
- cmd.ExecuteNonQuery();
- }
- }
- catch
- {
-
- }
- finally
- {
- if (conn.State == ConnectionState.Open)
- conn.Close();
- conn.Dispose();
- }
Method 2
- SqlConnection conn = new SqlConnection("your conn string here");
- SqlTransaction trans;
- SqlCommand cmd1 = new SqlCommand("UPDATE Table1 SET Column1=Value1",conn,trans);
- SqlCommand cmd2 = new SqlCommand("UPDATE Table2 SET Column2=Value2",conn,trans);
-
- if(condition1)
- {
- conn.Open();
- trans = conn.BeginTransaction();
- try
- {
-
- cmd1.ExecuteNonQuery();
- cmd2.ExecuteNonQuery();
- trans.Commit();
- conn.Close();
- }
- catch(Exception ex)
- {
- trans.Rollback();
- }
- finally
- {
- if(conn.State == ConnectionState.Open)
- {
- conn.Close();
- }
- }
- }
- else
- {
-
- }
thnx..
ReplyDelete