我在sql server中使用存储过程。 我有几个用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);
}
答案 0 :(得分:4)
您需要查看SqlTransaction
。
答案 1 :(得分: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();
}
}