-1

I am having issue to use SqlClient to call some sql query with parameter declared but not assigned. The query I want to run is similar to below

DECLARE @ID int;
SELECT @ID = OrderId
FROM Orders
ORDER BY OrderId DESC;
SELECT @ID;

However, when I created SqlParameter as following

SqlParameter parameter = new SqlParameter("ID", SqlDbType.Int);
sqlcommand.Parameters.Add(parameter);

I got error showing:

"The parameterized query
'(@ID int)SELECT @ID = OrderId
FROM Orders
ORDER BY OrderId DES'
expects the parameter '@ID', which was not supplied."

Any suggestions on how to create SqlParameter without any value assigned in such case?

1
  • 1
    If you are trying to use null you need to add the parameter with a value of DBNull.Value. If the stored procedure expects a value for the @ID field then you are required to provide one. Commented Jun 22, 2020 at 21:15

2 Answers 2

1

In your case you have to specify that @ID is an output parameter.

SqlParameter parameter = new SqlParameter("ID", SqlDbType.Int)
{
    Direction = ParameterDirection.Output
}

When the query will be executed you can retrieve that value via

parameter.Value

It will return an instance of the object type.

Sign up to request clarification or add additional context in comments.

1 Comment

I thought parameter direction only matters for stored procedure output parameter. did not know anything to return in the parameter needs to be specified as Output. Thank you!
0

First things first, it doesn't appear your query will return a single int, but many result rows that each contain an OrderId. You are selecting OrderId from every row in the table and trying to assign it to a single int variable - this won't work. If you just want the greatest OrderId, you can try SELECT TOP 1 @ID = OrderId as seen below.

To answer the question, the other answers are correct that you need to specify the parameter direction as output. Output parameters are different than input parameters.

SELECT TOP (1)
    @id = OrderId
FROM 
    Orders
ORDER BY 
    OrderId DESC;

1 Comment

You don't need a stored procedure to use output variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.