Share via


指定參數的方向

參數的方向不是入 (指將值傳入預存程序的輸入參數) 就是出 (指預存程序透過輸出參數傳回值給呼叫程式)。預設是輸入參數。

若要指定輸出參數,您必須在預存程序的參數定義中指定 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.