SQL Query says a parameter is not supplied, but is added to the SqlCommand object

后端 未结 4 631
南旧
南旧 2020-12-17 09:24

I have a stored procedure that has a parameter called UserName and in my code behind I have a SqlCommand object that I add the parameters to with the Add method. But for som

相关标签:
4条回答
  • 2020-12-17 09:45

    You will get this exception if the value of your 'userName' variable is null

    If null is valid, then pass 'DBNull.Value' to the db instead:

    command1.Parameters.Add(new SqlParameter("@UserName", (userName ?? DBNull.Value));   
    
    0 讨论(0)
  • 2020-12-17 09:49

    Try making sure that the command type is set to stored procedure.

    mycommand.CommandType = System.Data.CommandType.StoredProcedure;
    
    0 讨论(0)
  • 2020-12-17 09:55

    By default, the CommandText property needs to contain a complete SQL command, not just the name of the stored procedure.

    You can change this by to set the SqlCommand's CommandType property to StoredProcedure.

    Alternatively, you could explicitly pass the parameters, by changing the CommandText to "someStoredProcedure @UserName, @ProductCode"; this is a complete SQL statement and will work with the default CommandType of Text.

    EDIT: I just tried it, and the only way to get that error message without setting CommandType to StoredProcedure (which he did not do) is if CommandText is EXEC someStoredProcedure. Passing a null parameter gives a different error.

    0 讨论(0)
  • 2020-12-17 10:01
    Command1.CommandType = System.Data.CommandType.StoredProcedure
    

    This will force the ExecuteReader to perform the exec instead of just trying it as a flat command.

    0 讨论(0)
提交回复
热议问题