I’m trying to retrieve the return value of a stored procedure in SQL Server 2005 as follows:
OleDbCommand comm = new OleDbCommand(process_name, connection);
comm.CommandType = CommandType.StoredProcedure;
for (int i = 0; i < process_parameters.Length; i++)
comm.Parameters.AddWithValue(process_parameters[i].ParameterName, process_parameters[i].Value);
//Add output param
comm.Parameters.Add("@TestID", OleDbType.Integer).Direction = ParameterDirection.ReturnValue;
comm.ExecuteNonQuery();
When ExecuteNonQuery() is called, however, I get back a OleDbException saying: “Procedure or function myStoredProcedure has too many arguments specified.” My stored procedure begins as follows:
ALTER PROCEDURE [dbo].[spTabtempTestsINSERT]
(
@Param1 char (64),
@Param2 char (128),
@Param3 char (64),
)
AS
BEGIN
Declare @TestID int
And ends with the following:
RETURN @TestID
END
Does the fact that the return value is declared, rather than being passed as a parameter, have anything to do with it? If so, how can I get the return value of a param that’s declared after the stored procedure begins? Thanks for your help.
UPDATE:
I’ve tried the changes suggested so far, I added the following line:
OleDbCommand comm = new OleDbCommand(process_name, connection);
comm.CommandType = CommandType.StoredProcedure;
for (int i = 0; i < process_parameters.Length; i++)
comm.Parameters.AddWithValue(process_parameters[i].ParameterName, process_parameters[i].Value);
var testID = (int)comm.ExecuteScalar();
Now when ExecuteScalar() gets executed, I get a NullReferenceException with Object reference not set to an instance of an object.
Note: I also tried setting it to an integer int testID = (int)comm.ExecuteScalar(); and I still get the same error.
Ok, I was able to get it to work properly. My problem was that, I neglected to declare any of the parameters as OUTPUT, I added an extra variable and set that as the output variable and had the stored procedure return that. After word I just checked that output parameter ,after calling the stored procedure, from my C# code, the following shows the changes:
And at the end make a simple change:
Finally, back in my code:
Thank you all for your suggestions. Any alternatives or further insights are welcome.