两个表插入SQL事务

时间:2014-01-17 05:21:06

标签: c# sqltransaction

如何在前端用SQL事务实现两个表插入代码?

我有两个表,TblMasterTblSub。如果Tblsub插入失败,则应回滚TblMaster记录。

我在SQL帮助器类中有一个用于插入记录的公共函数ExecuteNonQuery

请建议我解决此问题的方法。

3 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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

答案 2 :(得分:0)

使用这样的transaction scope(您需要使用“添加引用”菜单项来引用项目中的System.Transactions .NET库):

using (TransactionScope scope = new TransactionScope())
{
    using (SqlConnection conn = new SqlConnection(<connectionString>))
    {
        conn.Open()

        try
        {
            // Do your stuff
            ...

            // Commit the transaction
            scope.Complete();
        }
        catch (...)
        {
            // Handle exceptions, transaction is rolled back automatically, as
            // "Complete" was not called
        }
    }
}