2017-10-12 62 views
2

我有一個存儲過程,它插入,刪除或更新我的數據庫中的行,並不返回任何值。我從我的C#代碼調用它是這樣的:C#存儲過程檢查是否成功

DAL.CDataContext dc = new DAL.CDataContext(); 
dc.MySproc(); 

如何檢查它是否成功運行?

+0

什麼是你'CDataContext()',你叫什麼'MySproc()'。無論如何,你可以嘗試'executenonquery':https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx – Jacky

+0

如果它沒有拋出,它運行成功。也許你的意思是別的嗎?不插入或不更新不是失敗。 –

+0

如果失敗,你不會得到一個異常嗎?所以如果你沒有得到例外,那一定是成功的......我只是在猜測 – musefan

回答

1

使用try catch。如果沒有異常,那麼查詢成功運行,那麼如果sucess返回true,返回false,如果它不是 例如

public static bool InsertObFile(PreApprove p) 
{ 
    var command = new SqlCommand(); 
    command.CommandText = "ObInsertPreApprove"; 
    command.CommandType = CommandType.StoredProcedure; 

    command.Parameters.AddWithValue("@EmployeeAutoId", p.EmployeeAutoId).Direction = ParameterDirection.Input; 
    command.Parameters.AddWithValue("@EmployeeId", p.EmployeeId).Direction = ParameterDirection.Input; 
    command.Parameters.AddWithValue("@DateFrom", p.DateFrom).Direction = ParameterDirection.Input; 
    command.Parameters.AddWithValue("@DateTo", p.DateTo).Direction = ParameterDirection.Input; 
    command.Parameters.AddWithValue("@Description", p.Description).Direction = ParameterDirection.Input; 
    command.Parameters.AddWithValue("@CreateUserId", p.CreateUserId).Direction = ParameterDirection.Input; 

    try 
    { 
     SqlHelper.ExecuteNonQuery(command); // this is where I run my stored procedure 
     return true; 
    } 
    catch (Exception e) 
    { 

     return false; 
    } 

} 
+1

但請(至少)記錄異常。不,你只知道發生了一些錯誤,但沒有詳細信息。 –