By: Greg Robidoux
Overview
In a previous topic we discussed how to pass parameters into a stored procedure, but another option is to pass parameter values back out from a stored procedure. One option for this may be that you call another stored procedure that does not return any data, but returns parameter values to be used by the calling stored procedure.
Explanation
Setting up output paramters for a stored procedure is basically the same as setting up input parameters, the only difference is that you use the OUTPUT clause after the parameter name to specify that it should return a value. The output clause can be specified by either using the keyword "OUTPUT" or just "OUT". For these examples we are still using the AdventureWorks database, so all the stored procedures should be created in the AdventureWorks database.
Simple Output
CREATE PROCEDURE dbo.uspGetAddressCount @City nvarchar(30), @AddressCount int OUTPUT AS SELECT @AddressCount = count(*) FROM AdventureWorks.Person.Address WHERE City = @City
Or it can be done this way:
CREATE PROCEDURE dbo.uspGetAddressCount @City nvarchar(30), @AddressCount int OUT AS SELECT @AddressCount = count(*) FROM AdventureWorks.Person.Address WHERE City = @City
To call this stored procedure we would execute it as follows. First we are going to declare a variable, execute the stored procedure and then select the returned valued.
DECLARE @AddressCount int EXEC dbo.uspGetAddressCount @City = 'Calgary', @AddressCount = @AddressCount OUTPUT SELECT @AddressCount
This can also be done as follows, where the stored procedure parameter names are not passed.
DECLARE @AddressCount int EXEC dbo.uspGetAddressCount 'Calgary', @AddressCount OUTPUT SELECT @AddressCount
Last Update: 3/24/2009