Advertisement
Intermediate SQL Server, Stored Procedures & Functions

How do you use output parameters in a stored procedure to return a value back to the calling code, in addition to or instead of a normal result set?

Short answer

You declare a parameter with the OUTPUT keyword in both the procedure definition and when calling it, and any value assigned to that parameter inside the procedure becomes available to the calling code after the procedure finishes executing, which is useful for returning things…

Save SQL Server mock interview
Advertisement
AModel answer
You declare a parameter with the OUTPUT keyword in both the procedure definition and when calling it, and any value assigned to that parameter inside the procedure becomes available to the calling code after the procedure finishes executing, which is useful for returning things like a newly generated identity value or a status code.
CREATE PROCEDURE CreateOrder
  @CustomerId INT,
  @NewOrderId INT OUTPUT
AS
BEGIN
  INSERT INTO Orders (CustomerId) VALUES (@CustomerId);
  SET @NewOrderId = SCOPE_IDENTITY();
END;

DECLARE @OrderId INT;
EXEC CreateOrder @CustomerId = 123, @NewOrderId = @OrderId OUTPUT;
Real-world example
An order creation procedure returns the newly generated order id back to the calling application using an output parameter, letting the application immediately know exactly which order was just created.
Likely follow-ups
  • What is the difference between SCOPE_IDENTITY and @@IDENTITY?
  • Can a stored procedure have multiple output parameters?
Related topics