指定参数的方向
参数的方向可以为 in(表明将值传递给存储过程的输入参数),也可以为 out(表明存储过程通过输出参数向调用程序返回值)。默认为输入参数。
若要指定输出参数,必须在存储过程的参数定义中指定 OUTPUT 关键字。当存储过程退出时,它将向调用程序返回输出参数的当前值。调用程序也必须使用 OUTPUT 关键字执行该存储过程,才能将该参数值保存到可以在调用程序中使用的变量中。有关详细信息,请参阅使用 OUTPUT 参数返回数据。
示例
下面的示例创建了 Production.usp_GetList 存储过程,该过程返回价格不超过指定金额的产品的列表。此示例显示如何使用多个 SELECT 语句和多个 OUTPUT 参数。使用 OUTPUT 参数,外部过程、批或多个 Transact-SQL 语句可以访问在过程执行期间设置的值。
USE AdventureWorks2008R2;
GO
IF OBJECT_ID ( 'Production.uspGetList', 'P' ) IS NOT NULL
DROP PROCEDURE Production.uspGetList;
GO
CREATE PROCEDURE Production.uspGetList @Product varchar(40)
, @MaxPrice money
, @ComparePrice money OUTPUT
, @ListPrice money OUT
AS
SET NOCOUNT ON;
SELECT p.[Name] AS Product, p.ListPrice AS 'List Price'
FROM Production.Product AS p
JOIN Production.ProductSubcategory AS s
ON p.ProductSubcategoryID = s.ProductSubcategoryID
WHERE s.[Name] LIKE @Product AND p.ListPrice < @MaxPrice;
-- Populate the output variable @ListPprice.
SET @ListPrice = (SELECT MAX(p.ListPrice)
FROM Production.Product AS p
JOIN Production.ProductSubcategory AS s
ON p.ProductSubcategoryID = s.ProductSubcategoryID
WHERE s.[Name] LIKE @Product AND p.ListPrice < @MaxPrice);
-- Populate the output variable @compareprice.
SET @ComparePrice = @MaxPrice;
GO
执行 usp_GetList 返回成本低于 700 美元的 Adventure Works 产品 (Bikes) 列表。OUTPUT 参数 @cost 和 @compareprices 与控制流语言一起使用,在**“消息”**窗口返回一条消息。
注意 |
---|
OUTPUT 变量必须在过程创建和变量使用期间进行定义。参数名称和变量名称不一定要匹配。但是,数据类型和参数定位必须匹配(除非使用 @listprice= variable)。 |
DECLARE @ComparePrice money, @Cost money
EXECUTE Production.uspGetList '%Bikes%', 700,
@ComparePrice OUT,
@Cost OUTPUT
IF @Cost <= @ComparePrice
BEGIN
PRINT 'These products can be purchased for less than
$'+RTRIM(CAST(@ComparePrice AS varchar(20)))+'.'
END
ELSE
PRINT 'The prices for all products in this category exceed
$'+ RTRIM(CAST(@ComparePrice AS varchar(20)))+'.'
下面是部分结果集:
Product List Price
-------------------------------------------------- ------------------
Road-750 Black, 58 539.99
Mountain-500 Silver, 40 564.99
Mountain-500 Silver, 42 564.99
...
Road-750 Black, 48 539.99
Road-750 Black, 52 539.99
(14 row(s) affected)
These items can be purchased for less than $700.00.