Using SQL Server output parameters in stored procedures
A stored procedure often needs to give the caller more than a success flag. A generated order number, validation code or affected-row count can all travel back through a SQL Server output parameter. The mechanism is compact, although its behaviour differs from both a result set and the DML OUTPUT clause.
A well-defined output contract can keep database operations tidy and make them easier to consume from an API service. It also avoids exposing table structures directly to browser clients while preserving a clear, testable boundary between SQL Server and application code.
What output parameters return
In Transact-SQL, the OUTPUT keyword marks a stored procedure parameter as an output. The procedure can assign a value during execution, and the caller receives that value through a local variable declared before calling the procedure.
CREATE OR ALTER PROCEDURE dbo.GetOrderStatus
@OrderId int,
@StatusCode int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT @StatusCode = StatusCode
FROM dbo.Orders
WHERE OrderId = @OrderId;
END;
The caller supplies the input parameters normally and adds OUTPUT after the output argument. A result set remains available when the procedure needs to return rows, so output parameters can accompany query results rather than replacing them.
DECLARE @StatusCode int = NULL;
EXEC dbo.GetOrderStatus
@OrderId = 1042,
@StatusCode = @StatusCode OUTPUT;
SELECT @StatusCode AS StatusCode;
An output parameter differs from RETURN, which provides only an integer status code. It also differs from a result set because it represents one known value rather than an arbitrary collection of rows. Several output parameters can describe one operation, such as an identifier, creation timestamp and validation result.
Declaring and reading output parameters
The receiving variable must exist before the EXEC statement. Its type should match the procedure definition, including any important precision or length. Leaving the variable at NULL provides a useful default when a procedure finds no matching row and never assigns its output.
Although SQL Server allows an output parameter to accept an input value as well, separate input and output variables often make the contract easier to understand. Developers can inspect sys.parameters and its is_output column when documenting or reviewing a procedure’s signature.
Output parameters work best for small, predictable values. Returning a complete customer record through dozens of output parameters is difficult to maintain and produces a brittle interface. A result set is more natural when the caller needs multiple columns, many rows or data whose shape may evolve.
Capturing generated identifiers
A common requirement is returning the identity value generated by an INSERT. A procedure can insert the row, capture the identity with SCOPE_IDENTITY() and assign it to its output parameter.
CREATE OR ALTER PROCEDURE dbo.CreateCustomer
@Email nvarchar(320),
@CustomerId int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO dbo.Customers (Email)
VALUES (@Email);
SET @CustomerId = CONVERT(int, SCOPE_IDENTITY());
END;
The DML OUTPUT clause offers another route. Used directly after the INSERT, it returns the generated value as a result set. A single-row table variable can capture that value instead when the procedure needs to avoid producing an extra result set.
DECLARE @InsertedIds TABLE (CustomerId int);
INSERT INTO dbo.Customers (Email)
OUTPUT INSERTED.CustomerId INTO @InsertedIds
VALUES (@Email);
SELECT @CustomerId = CustomerId
FROM @InsertedIds;
This example assumes an integer identity and exactly one inserted row. A uniqueidentifier key can be returned in the same fashion by giving the output parameter the matching type. Australian applications commonly display dates as 04/11/2026 and amounts in Australian dollars, while daylight-saving changes make local wall-clock times ambiguous. These conventions belong in the presentation layer; identifiers, UTC timestamps and decimal monetary values should retain unambiguous database representations.
Returning values from updates and deletes
Updates and deletes often need to communicate whether anything matched. Capturing @@ROWCOUNT immediately after the statement gives the caller an exact affected-row count without adding another result set.
CREATE OR ALTER PROCEDURE dbo.CancelOrder
@OrderId int,
@CancelledRows int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
UPDATE dbo.Orders
SET StatusCode = 'CANCELLED'
WHERE OrderId = @OrderId;
SET @CancelledRows = @@ROWCOUNT;
END;
The DML OUTPUT clause can expose inserted and deleted column values at the same time. For example, an update can return both the previous and new status. Assigning a multi-row result to a scalar output parameter causes an error, so procedures must use a unique key, an aggregate such as @@ROWCOUNT, a table variable or a regular result set when several records may match.
For an Australian retailer operating a .com.au storefront, cancellation, GST records and Business Activity Statement workflows make auditing important. A cancellation or void status with an affected-row count is generally more useful than physically deleting every invoice-related row. The procedure should preserve records according to the business’s applicable GST and Australian Taxation Office record-retention obligations.
Handling transactions and result sets
Output parameters are not transactional in the same way as inserted or updated table rows. An assigned value can remain visible after a rollback, so the application must not treat a populated output as proof that the transaction committed. Assigning the final output only after a successful commit avoids ambiguity.
CREATE OR ALTER PROCEDURE dbo.CreateOrder
@CustomerId int,
@OrderId int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @CreatedOrderId int;
BEGIN TRY
BEGIN TRANSACTION;
INSERT INTO dbo.Orders (CustomerId)
VALUES (@CustomerId);
SET @CreatedOrderId = CONVERT(int, SCOPE_IDENTITY());
COMMIT TRANSACTION;
SET @OrderId = @CreatedOrderId;
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0
ROLLBACK TRANSACTION;
THROW;
END CATCH
END;
SET NOCOUNT ON prevents row-count messages from adding unnecessary network traffic, while @@ROWCOUNT remains available inside the procedure. A stored procedure may also return both result sets and output parameters. Consumers should finish reading any result set before relying on the final output values.
For organisations covered by the Privacy Act 1988 and the Australian Privacy Principles, a narrow stored procedure interface can support data minimisation and controlled access. Returning only required identifiers and status values reduces exposure, but procedural encapsulation alone does not establish regulatory compliance. Access controls, audit logging and secure infrastructure remain necessary.
Connecting stored procedures to .NET applications
In .NET, an output parameter maps directly to ParameterDirection.Output. The application declares the parameter, executes the procedure and reads its value after execution. Parameterised commands also protect values such as email addresses from accidental SQL injection.
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
await using var command = new SqlCommand("dbo.CreateCustomer", connection);
command.CommandType = CommandType.StoredProcedure;
var email = command.Parameters.Add("@Email", SqlDbType.NVarChar, 320);
email.Value = customer.Email;
var customerId = command.Parameters.Add("@CustomerId", SqlDbType.Int);
customerId.Direction = ParameterDirection.Output;
customerId.Value = DBNull.Value;
await command.ExecuteNonQueryAsync();
int newCustomerId = (int)customerId.Value;
The output belongs in the server-side data-access layer, not in a response that exposes SQL Server directly to Angular. The client-side half of that flow is covered in my guide to Angular and .NET integration, which shows how an Angular application calls a .NET endpoint over HttpClient.
Many teams in Sydney and Melbourne use .NET alongside SQL Server, and Azure SQL deployments in Australia East or Australia Southeast can suit local latency and residency requirements. Availability and data-handling terms still need checking for the chosen service. If a procedure returns rows as well as outputs, the .NET code should consume and close the reader before reading the final output values.
Put the pattern to work
Use an output parameter when the caller needs one or a few known scalar values, such as an identifier, status code or affected-row count. Use a result set for row-oriented data. Test missing rows, multiple matches, null values, permission failures and transaction rollbacks so the contract behaves predictably under real conditions.
Create a disposable SQL Server database today, implement dbo.CreateCustomer and call it from a small .NET console application. Include a duplicate-email failure and a rollback case, then carry the proven contract into the API layer your team maintains.