【问题标题】:Get Error Message in SQL Server stored procedure to VB.NET program将 SQL Server 存储过程中的错误消息获取到 VB.NET 程序
【发布时间】:2016-07-07 07:16:42
【问题描述】:

我在 SQL Server 2014 Express 中有一个这样的存储过程:

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 windows 窗体程序中显示此消息。

在我的表单中,我添加了 1 个按钮和 1 个数据网格视图。

我在方法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 程序中未显示错误。

那么,我应该编写什么代码来显示存储过程中的错误?

【问题讨论】:

  • 您是否尝试使用dt.Load(cmd.ExecuteReader()) 填充DataTable,而不是使用DataAdapter?参考:MarkN 在SqlDataAdapter and RAISERRORs 的倒数第二个帖子。
  • 第一个 MessageBox(你应该在 .Net 中使用它而不是旧的 VB6 MsgBox)是否显示计数?通常,我不会为那个或For Each ... Next 循环而烦恼。我的错误处理程序通常只会做MessageBox.Show(SQLex.ToString)ToString 显示了异常的全部细节,所以它不是很漂亮,而 Message 属性只显示消息描述。

标签: sql-server vb.net winforms stored-procedures


【解决方案1】:

我从 Andrew Morton 的评论中找到了答案。 我使用 dt.Load(cmd.ExecuteReader()) 并且它有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多