【问题标题】:Calling SQL Server stored procedure from VB.NET application. Output parameter is coming back blank从 VB.NET 应用程序调用 SQL Server 存储过程。输出参数返回空白
【发布时间】:2016-03-20 11:33:04
【问题描述】:

我试图调用一个简单的存储过程,它从 VB.NET 应用程序返回一个 OUTPUT 参数,但是当我尝试显示结果时,它显示为空白。代码没有抛出任何异常,当我在 SQL Server Mgmt studio 中执行 SP 时,它会按预期返回。我可能只是忽略了一些东西。感谢任何建议。 SP和VB代码如下:

SP 代码:

create procedure [dbo].[get_number_potential_matches] @deductnRecId int, @numberPotentialMatches int output as 
begin 
    select numberPotentialMatches = count(*) 
    from potential_match pm 
    where pm.deductn_rec_id = @deductnRecId;
    return
end

VB.Net 程序:

Sub getPotentialMatchCount(ByVal deductnRecId As Integer)
    Try
        SqlCmd = New SqlCommand("get_number_potential_matches", SqlConn)
        SqlCmd.CommandType = CommandType.StoredProcedure
        SqlCmd.Parameters.Add("@deductnRecId", SqlDbType.Int).Value = deductnRecId
        SqlCmd.Parameters("@deductnRecId").Direction = ParameterDirection.Input

        SqlCmd.Parameters.Add("@numberPotentialMatches", SqlDbType.Int)
        SqlCmd.Parameters("@numberPotentialMatches").Direction = ParameterDirection.Output

        SqlConn.Open()
        SqlCmd.ExecuteNonQuery()

    Catch ex As Exception
        lbl_pm.Text = ex.Message
    Finally
        SqlCmd.Dispose()
        SqlConn.Close()
    End Try
    lbl_pm.Text = "deductnRecId: " & deductnRecId.ToString & " has " & SqlCmd.Parameters("@numberPotentialMatches").Value.ToString() & " matches"
End Sub

【问题讨论】:

  • 您正在最终处理 SqlCmd 对象,但之后尝试获取参数的值。顺便说一句,最好在 Using 语句中初始化 Connection 和 Command 对象,这将隐式处理对象。

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


【解决方案1】:

您在 SP 的参数名称中遗漏了“@”。应该是

select @numberPotentialMatches = count(*) ...

您所做的是选择count(*) 并将numberPotentialMatches 设置为列别名。

另外,在 SqlCmd 被处理后不要访问它。

【讨论】:

  • 他在dispose之后也在使用SqlCmd对象,不好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多