简体   繁体   English

已传递MS SQL查询参数,但在VB.net中无法识别

[英]MS SQL query parameter passed, but not recognized in VB.net

I've been banging my head against this for a while now. 我已经为此努力了一段时间。

I have a function that retrieves fields from a table and populates inputs from them, however when I try to execute the function I receive an error saying "Procedure or function 'Quad_GetAllFields' expects parameter '@subWeek', which was not supplied". 我有一个从表中检索字段并从中填充输入的函数,但是,当我尝试执行该函数时,收到一条错误消息:“过程或函数'Quad_GetAllFields'需要参数'@subWeek',但未提供”。

I know I am supplying the parameter, as I can access it from any point in the function. 我知道我正在提供参数,因为我可以从函数的任何位置访问它。

The function is: 该函数是:

Protected Sub setAllFields(ByVal myConnection As SqlConnection, ByVal subWeek As String, ByVal site As String)
    Dim myCommand = New SqlCommand("Quad_GetAllFields", myConnection)
    myCommand.Parameters.AddWithValue("@subWeek", subWeek)
    myCommand.Parameters.AddWithValue("@site", site)
    Dim myDataReader As SqlDataReader = myCommand.ExecuteReader()
    If myDataReader.Read() Then
        'populate fields
    End If
End Sub

And the stored procedure is: 存储过程为:

ALTER PROCEDURE dbo.Quad_GetAllFields
(
@subWeek VARCHAR(50),
@site VARCHAR(20)   
)
AS
BEGIN
SELECT TOP (1) ID, Priority1, Priority2, Priority3, Priority4, Highlight1, Highlight2, Highlight3, Highlight4, Update1, Update2, Update3, Ahead1, Ahead2, Ahead3, Outlook1, Outlook2, Comments, Site, Week, Submitted FROM Charts WHERE Week = @subWeek AND Site = @site ORDER BY ID DESC
END

Any help on what I'm doing wrong? 对我做错了什么有帮助吗?

I'm fairly new in working with stored procedures, but I still can't find the problem. 我在使用存储过程方面还很陌生,但是仍然找不到问题。

Thank you 谢谢

You have to set the SqlCommand's CommandType property to StoredProcedure , default is Text : 您必须将SqlCommand's CommandType属性设置为StoredProcedure ,默认为Text

Protected Sub setAllFields(ByVal myConnection As SqlConnection, ByVal subWeek As String, ByVal site As String)
    Dim myCommand = New SqlCommand("Quad_GetAllFields", myConnection)
    myCommand.CommandType = CommandType.StoredProcedure
    myCommand.Parameters.AddWithValue("@subWeek", subWeek)
    myCommand.Parameters.AddWithValue("@site", site)
    Dim myDataReader As SqlDataReader = myCommand.ExecuteReader()
    If myDataReader.Read() Then
        'populate fields'
    End If
End Sub

If your string parameter, @subWeek, is null you can get this error. 如果您的字符串参数@subWeek为空,则会出现此错误。

If your string is null, you need to pass DBNull.Value for @subWeek. 如果字符串为null,则需要为@subWeek传递DBNull.Value。

Try hard-coding a @subWeek value 尝试对@subWeek值进行硬编码

myCommand.Parameters.AddWithValue("@subWeek", "Myvalue")

This should work fine. 这应该工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM