1

フロントエンドでSQLトランザクションを使用して2つのテーブル挿入コードを実装する方法は?

私は2つのテーブルを持っていTblMasterますTblSub. Tblsub挿入が失敗した場合、レコードTblMasterはロールバックされます。

ExecuteNonQueryレコードを挿入するための SQL ヘルパー クラスに共通の関数があります。

この問題を解決する方法を教えてください。

4

3 に答える 3

3

C# での例

SqlTransaction transaction = null;
SqlConnection con = null;

// they will be used to decide whether to commit or rollback the transaction
bool debitResult = false;
bool creditResult = false;

try
{
    con = new SqlConnection(CONNECTION_STRING);
    con.Open();

    // lets begin a transaction here
    transaction = con.BeginTransaction();

    // Let us do a debit first
    using (SqlCommand cmd = con.CreateCommand())
    {
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "Insert into Table1";   // Query here

        // assosiate this command with transaction
        cmd.Transaction = transaction;

        debitResult = cmd.ExecuteNonQuery() == 1;
    }

    // A dummy throw just to check whether the transaction are working or not
    //throw new Exception("Let see..."); // uncomment this line to see the transaction in action

    // And now do a credit
    using (SqlCommand cmd = con.CreateCommand())
    {
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "Insert into Table2";   // Query here

        // assosiate this command with transaction
        cmd.Transaction = transaction;

        creditResult = cmd.ExecuteNonQuery() == 1;
    }

    if (debitResult && creditResult)
    {
        transaction.Commit();
    }
}
catch
{
    transaction.Rollback();            
}
finally
{
    con.Close();
}
于 2014-01-17T05:26:08.677 に答える
1

この方法を試してください

BEGIN TRANSACTION tran1
  BEGIN  TRY
    --Insert into Table1
    --Insert into Table2
COMMIT TRANSACTION  tran1                           
  END TRY

BEGIN CATCH
   ROLLBACK TRANSACTION tran1 
      raiserror('Cannot commite transaction',16,1,@@error);
   return;
END CATCH
于 2014-01-17T05:23:46.653 に答える