Stored procedure or function expects parameter which is not supplied
In my case I received this exception even when all parameter values were correctly supplied but the type of command was not specified :
cmd.CommandType = System.Data.CommandType.StoredProcedure;
This is obviously not the case in the question above, but exception description is not very clear in this case, so I decided to specify that.
I came across this issue yesterday, but none of the solutions here worked exactly, however they did point me in the right direction.
Our application is a workflow tool written in C# and, overly simplified, has several stored procedures on the database, as well as a table of metadata about each parameter used by each stored procedure (name, order, data type, size, etc), allowing us to create as many new stored procedures as we need without having to change the C#.
Analysis of the problem showed that our code was setting all the correct parameters on the SqlCommand
object, however once it was executed, it threw the same error as the OP got.
Further analysis revealed that some parameters had a value of null
. I therefore must draw the conclusion that SqlCommand
objects ignore any SqlParameter
object in their .Parameters
collection with a value of null
.
There are two solutions to this problem that I found.
In our stored procedures, give a default value to each parameter, so from
@Parameter int
to@Parameter int = NULL
(or some other default value as required).In our code that generates the individual
SqlParameter
objects, assigningDBNull.Value
instead ofnull
where the intended value is a SQLNULL
does the trick.
The original coder has moved on and the code was originally written with Solution 1 in mind, and having weighed up the benefits of both, I think I'll stick with Solution 1. It's much easier to specify a default value for a specific stored procedure when writing it, rather than it always being NULL
as defined in the code.
Hope that helps someone.