2011-01-22 48 views
2

我正在使用SQL Server中的存储过程。 我有几个用c#编写的存储过程调用。我想在交易中包装它们:创建事务到存储过程调用c#

//Begin Transaction here 
sp1Call(); 
sp2Call(); 
sp3Call(); 
//Commit here 
//Rollback if failed 

有没有办法做到这一点?

更新: 我正在使用企业库。例如sp1Call():

public static void sp1Call(string itemName) 
    { 
     DbCommand command = db.GetStoredProcCommand("dbo.sp1_insertItem"); 
     db.AddInParameter(command, "@item_name", DbType.String, itemName); 
     db.ExecuteNonQuery(command); 
    } 
+2

你怎么称呼你的程序?你使用什么客户端API? – alexn 2011-01-22 17:14:36

+0

我正在使用企业库。请参阅更新。 – Naor 2011-01-22 17:25:27

回答

4

你会想看看SqlTransaction

+0

请参阅更新。你能给个例子吗? – Naor 2011-01-22 17:27:43

2

只是一个快速搜索想出了DBTransaction

using (DbConnection connection = db.CreateConnection()) 
    { 
    connection.Open(); 
    DbTransaction transaction = connection.BeginTransaction(); 
    try 
    { 
     DbCommand command = db.GetStoredProcCommand("dbo.sp1_insertItem"); 
     db.AddInParameter(command, "@item_name", DbType.String, itemName); 
     db.ExecuteNonQuery(command, transaction); 
     transaction.Commit();     
    } 
    catch 
    { 
     //Roll back the transaction. 
     transaction.Rollback(); 
    } 
    }