-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?

Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
katrinawyh
  • 23
  • 3
  • 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. – Jacob Huckins Jun 22 '20 at 21:15

2 Answers2

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.

  • 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! – katrinawyh Jun 22 '20 at 23:03
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;
Brent George
  • 108
  • 2
  • 11