参数用于在存储过程和调用存储过程的应用程序或工具之间交换数据:
下面的存储过程说明了输入参数、输出参数和返回代码的使用:
USE Northwind
GO
-- Create a procedure that takes one input parameter
-- and returns one output parameter and a return code.
CREATE PROCEDURE SampleProcedure @EmployeeIDParm INT,
@MaxQuantity INT OUTPUT
AS
-- Declare and initialize a variable to hold @@ERROR.
DECLARE @ErrorSave INT
SET @ErrorSave = 0
-- Do a SELECT using the input parameter.
SELECT FirstName, LastName, Title
FROM Employees
WHERE EmployeeID = @EmployeeIDParm
-- Save any nonzero @@ERROR value.
IF (@@ERROR <> 0)
SET @ErrorSave = @@ERROR
-- Set a value in the output parameter.
SELECT @MaxQuantity = MAX(Quantity)
FROM [Order Details]
IF (@@ERROR <> 0)
SET @ErrorSave = @@ERROR
-- Returns 0 if neither SELECT statement had
-- an error; otherwise, returns the last error.
RETURN @ErrorSave
GO
执行存储过程时,输入参数既可以将它们的值设置为常量也可以使用变量的值。输出参数和返回代码必须将其值返回变量。参数和返回代码可以与 Transact-SQL 变量或应用程序变量交换数据值。
如果从批处理或脚本调用存储过程,则参数和返回代码值可以使用在同一个批处理中定义的 Transact-SQL 变量。下面示例是执行以前创建的过程的批处理。输入参数被指定为常量,输出参数和返回代码将它们的值放在 Transact-SQL 变量中:
-- Declare the variables for the return code and output parameter. DECLARE @ReturnCode INT DECLARE @MaxQtyVariable INT -- Execute the stored procedure and specify which variables -- are to receive the output parameter and return code values. EXEC @ReturnCode = SampleProcedure @EmployeeIDParm = 9, @MaxQuantity = @MaxQtyVariable OUTPUT -- Show the values returned. PRINT ' 'PRINT 'Return code = ' + CAST(@ReturnCode AS CHAR(10)) PRINT 'Maximum Quantity = ' + CAST(@MaxQtyVariable AS CHAR(10)) GO
应用程序可以通过绑定到程序变量的参数标记在应用程序变量、参数和返回代码之间交换数据。