Read SQL output parameters after closing the data reader
A command can return rows and output parameters, but its output values are not available until the reader is closed. Keep the reader's lifetime inside the command's lifetime, then read those parameters.
Use explicit SQL types rather than inferring them from arbitrary CLR values. CommandTimeout is measured in seconds.
Execute a self-contained batch
Requires a reachable SQL Server and a .NET console project with dotnet add package Microsoft.Data.SqlClient. Set DEMO_SQL_CONNECTION to an authorized connection string through your environment, then use this Program.cs:
using System.Data;
using Microsoft.Data.SqlClient;
var cs = Environment.GetEnvironmentVariable("DEMO_SQL_CONNECTION")
?? throw new InvalidOperationException("Set DEMO_SQL_CONNECTION.");
await using var connection = new SqlConnection(cs);
await connection.OpenAsync();
using var command = new SqlCommand("SELECT 7 AS Value; SET @Total = 12.50;", connection);
command.CommandTimeout = 30;
var total = command.Parameters.Add("@Total", SqlDbType.Decimal);
total.Precision = 10; total.Scale = 2; total.Direction = ParameterDirection.Output;
await using (var reader = await command.ExecuteReaderAsync()) {
while (await reader.ReadAsync()) Console.WriteLine(reader.GetInt32(0));
}
Console.WriteLine(((decimal)total.Value).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
Run dotnet run. Expect 7 and 12.50. No table or stored procedure is created.
Adapt it to a procedure
Set CommandType.StoredProcedure, use the procedure name as command text, and declare each parameter with its actual type, length, precision and scale. Handle DBNull.Value when an output may be SQL NULL. Consume additional result sets with NextResultAsync when needed, and close the reader before reading output or return-value parameters.
Official references


Author: Herman Schoenfeld