VB.NET Try Catch 未捕获 SQL Server 存储过程中引发的错误

问题描述 投票:0回答:1

在 VB.NET 中,我调用带有 1 个参数的存储过程并使用

CommandType.StoredProcedure

在存储过程中,我根据我正在测试的某些标准生成

RAISEERROR

当我按照这种安排在 VB 中执行 SQL 时,它不会捕获错误或至少会生成一个消息框

当我改为使用

CommandType.Text
并使用

EXEC StoredProcNameHere 'parametervaluehere'

它确实显示了这个消息框,其中包含我期待的错误。

我是否有什么设置不正确的地方?

这就是我想要的工作(替换专有值):

Using con As New SqlClient.SqlConnection("Connection String Here")
    Using cmd As New SqlClient.SqlCommand
        With cmd
            .Connection = con
            .CommandType = CommandType.StoredProcedure
            .CommandText = "StoredProcHere"
            .Parameters.Add("@Param", SqlDbType.Char).Value = oFunctions.Enquote(paramvalue)
        End With
        con.Open()
        Try
            cmd.ExecuteNonQuery()
        Catch ex As SqlClient.SqlException
            MsgBox(ex.Message, vbExclamation, "Title")
        End Try
        con.Close()
    End Using
End Using

这就是有效的:

Using con As New SqlClient.SqlConnection("Connection String Here")
    Using cmd As New SqlClient.SqlCommand
        With cmd
            .Connection = con
            .CommandType = CommandType.Text
            .CommandText = "EXEC StoredProcedure " & oFunctions.Enquote(param)
        End With
        con.Open()
        Try
            cmd.ExecuteNonQuery()
        Catch ex As SqlClient.SqlException
            MsgBox(ex.Message, vbExclamation, "Title")
        End Try
        con.Close()
    End Using
End Using

oFunctions.Enquote
只是将参数用单引号括起来 (
'
)。

sql-server vb.net stored-procedures try-catch sqlexception
1个回答
-1
投票

问题在于引用参数值,正如 @ThomA 指出的那样,

谢谢你汤姆!

© www.soinside.com 2019 - 2024. All rights reserved.