简体   繁体   中英

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".

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 :

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.

If your string is null, you need to pass DBNull.Value for @subWeek.

Try hard-coding a @subWeek value

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

This should work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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