If the stored procedure is guaranteed to return exactly one record, then using ExecuteReader() with a while loop is not necessary — you can use a single if (rdr.Read()) or even ExecuteScalar() if you only expect one value.
However, since you mentioned you don’t know the column names yet (only the index positions), preparing your code to handle results by index is a good idea. Here’s how you can structure it safely:
using (SqlCommand cmd = new SqlCommand("YourStoredProcedureName", connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Device", "White group");
cmd.Parameters.AddWithValue("@NumCount", numCount);
// Return value parameter
var returnParameter = cmd.Parameters.Add("@returnCode", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
using (var rdr = cmd.ExecuteReader())
{
if (rdr.Read()) // Only one record expected
{
var firstIdentifier = rdr.GetInt32(0);
var lastIdentifier = rdr.GetInt32(1);
var numCountResponse = rdr.GetInt32(2);
}
}
int returnCode = (int)returnParameter.Value;
Console.WriteLine($"Return Code: {returnCode}");
}
How the return code works
The return value (@returnCode) is not part of the result set.
It is a special output parameter returned by the stored procedure itself (via a RETURN statement).
You can name it anything you like in your C# code — the important part is setting
returnParameter.Direction = ParameterDirection.ReturnValue;
Inside your SQL stored procedure, you’ll usually see something like:
CREATE PROCEDURE YourStoredProcedure
@Device NVARCHAR(50),
@NumCount INT
AS
BEGIN
-- logic here
RETURN 1 -- or any integer
END
So, to summarize:
Use ExecuteReader() if you’re reading fields from a record.
Use ParameterDirection.ReturnValue to capture the procedure’s return code.
- The return value is not a column — it’s a separate output from the stored procedure.If the stored procedure is guaranteed to return exactly one record, then using
ExecuteReader()with awhileloop is not necessary — you can use a singleif (rdr.Read())or evenExecuteScalar()if you only expect one value. However, since you mentioned you don’t know the column names yet (only the index positions), preparing your code to handle results by index is a good idea. Here’s how you can structure it safely:
How the return code worksusing- The return value (
@returnCode) is not part of the result set. - It is a special output parameter returned by the stored procedure itself (via a
RETURNstatement). - You can name it anything you like in your C# code — the important part is setting
returnParameter.Direction = ParameterDirection.ReturnValue; - Inside your SQL stored procedure, you’ll usually see something like:
CREATE
- Use
ExecuteReader()if you’re reading fields from a record. - Use
ParameterDirection.ReturnValueto capture the procedure’s return code. - The return value is not a column — it’s a separate output from the stored procedure.
- The return value (