2016-07-07 82 views
1

我在SQL Server中的存儲過程2014和快遞這樣的:獲取錯誤消息VB.NET程序

CREATE PROCEDURE dtUmum.prCoba 
AS 
BEGIN 
BEGIN TRY 
    SET NOCOUNT ON; 
    SELECT 1/0; 
    SET NOCOUNT OFF; 
END TRY 
BEGIN CATCH 
    DECLARE @varErrorMessage NVARCHAR(4000), @varErrorSeverity INT, @varErrorState INT; 
    SELECT @varErrorMessage = ERROR_MESSAGE(), @varErrorSeverity = ERROR_SEVERITY(), @varErrorState = ERROR_STATE(); 
    RAISERROR(@varErrorMessage,@varErrorSeverity,@varErrorState); 
END CATCH; 
END 

如果我執行存儲過程在SQL Server Management Studio中是這樣的:

EXECUTE dtUmum.prCoba; 

我得到這個錯誤的信息標籤:

消息50000,級別16,狀態1,過程prCoba,33號線
除以零遇到的錯誤。

我想這個消息顯示在我的vb.net窗口窗體程序中。

在我的表單中,我添加了1個按鈕和1個datagridview。

我的方法button_click這樣的代碼:

Try 
    Using cn As New SqlConnection("Server=.\SQLEXPRESS;Database=myDB;Integrated Security=True") 
     cn.Open() 
     Using cmd As New SqlCommand() 
      cmd.Connection = cn 
      cmd.CommandType = CommandType.StoredProcedure 
      cmd.CommandText = "dtUmum.prCoba" 
      Using da As New SqlDataAdapter(cmd) 
       Dim dt As New DataTable 
       da.Fill(dt) 
       da.FillSchema(dt, SchemaType.Source) 
       Me.DataGridView1.DataSource = dt 
      End Using 
     End Using 
     cn.Close() 
    End Using 
Catch SQLex As SqlException 
    Dim SSS As SqlError 
    MsgBox("Count = " & SQLex.Errors.Count) 
    For Each SSS In SQLex.Errors 
     MsgBox(SSS.Message) 
    Next 
End Try 

此代碼不能在我的vb.net程序顯示錯誤。

那麼,我應該寫什麼代碼來顯示存儲過程中的錯誤?

+0

而不是使用DataAdapter,你嘗試用'dt.Load(cmd.ExecuteReader())'填充DataTable嗎?參考:MarkN在[SqlDataAdapter和RAISERRORs]的倒數第二個帖子(https://social.msdn.microsoft.com/Forums/zh-CN/ad135c3f-2afb-40aa-9eff-28cff08514c3/sqldataadapter-and-raiserrors?forum=adodotnetdataproviders) 。 –

+0

第一個MessageBox(你應該在.Net而不是舊的VB6 MsgBox中使用它)顯示計數嗎?通常情況下,我不會爲此或「For Each ... Next」循環而煩惱。我的錯誤處理程序通常只會執行'MessageBox.Show(SQLex.ToString)'。 'ToString'顯示異常的完整細節,所以它不是很漂亮,而'Message'屬性只顯示消息描述。 – topshot

回答

0

我從Andrew Morton的評論中找到了答案。 我使用dt.Load(cmd.ExecuteReader()),它是工作。