2014-03-26 19 views
-2

我有3個存儲過程在3個不同的表上,其主要目的是插入,刪除,查看和更新​​。使用存儲過程操作數據,使用c處理數據#

我有一個註冊表單,其中包含9個字段,需要由用戶填寫。一旦用戶點擊提交,前3個字段數據將被髮送到第一SP,接下來的3到第二個SP,以及最後3到第三個SP。

我正在尋找執行事務來做到這一點..這樣,如果所有的數據成功添加,它的提交或否則整個數據應該回滾。

string connectionString = 
WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString; 
SqlConnection con = new SqlConnection(connectionString); 
SqlCommand cmd1 = new SqlCommand(con, CommandType.StoredProcedure, "usp_additemdata",  p); 
SqlCommand cmd2 = new SqlCommand(con, CommandType.StoredProcedure, "usp_addpricedata", p) 
SqlTransaction tran = null; 
try 
{ 

con.Open(); 

cmd1.Transaction = tran; 
cmd2.Transaction = tran; 

cmd1.ExecuteNonQuery(); 
cmd2.ExecuteNonQuery(); 
Commit the transaction. 
tran.Commit(); 
} 
catch 
{ 

tran.Rollback(); 
} 
finally 
{ 
con.Close(); 
} 
+0

你嘗試過這麼遠嗎?如果您在編寫的代碼中遇到問題,我們可以幫助您解決問題,但不能編寫完整的代碼。 – Junaith

回答

0

您可以使用Transaction Scope這裏

using (TransactionScope scope = new TransactionScope()) 
    { 
     using (SqlConnection connection1 = new SqlConnection(yourconnectionstring)) 
     { 
      //your commands here 
     } 

     // The Complete method commits the transaction. If an exception has been thrown, 
     // Complete is not called and the transaction is rolled back. 
     scope.Complete(); 
    } 
0
SqlConnection db = new SqlConnection("ConnectionStringHere"); 
     SqlTransaction transaction; 

    db.Open(); 
    transaction = db.BeginTransaction(); 
    try 
    { 
    var SqlC1= new SqlCommand("SP1", db, transaction); 
    <Add parameters in SqlC1> 
     SqlC1.ExecuteNonQuery(); 
    var SqlC2= new SqlCommand("SP2", db, transaction); 
    <Add parameters in SqlC2> 
     SqlC2.ExecuteNonQuery(); 

    var SqlC3= new SqlCommand("SP3", db, transaction); 
    <Add parameters in SqlC3> 
     SqlC3.ExecuteNonQuery(); 
    transaction.Commit(); 
    } 
    catch (SqlException sqlError) 
    { 
    transaction.Rollback(); 
    } 
    db.Close();**strong text** 
+0

謝謝你的解決方案..它爲我工作,但需要一個小的代碼除了執行SP .. 1)var SqlC1 =新的SqlCommand(「SP1」,數據庫,交易); 2)<<< sqlC1.CommandType = CommandType.StoredProcedure >>>> 3)<在SqlC1中添加參數> 4)SqlC1.ExecuteNonQuery(); 與第二個聲明的代碼沒有工作......但它工作正常,如果SQL查詢直接傳遞 – Itniv

+0

你可以分享真實的代碼,以更多的理解... –

+0

即時消息新張貼..你要我發佈爲答案或..作爲評論..? – Itniv

相關問題