细化解析:如何使用OUTPUT参数返回数据

来源:岁月联盟 编辑:zhuzhu 时间:2007-10-24

如果在过程定义中为参数指定 OUTPUT 关键字,则存储过程在退出时可将该参数的当前值返回至调用程序。若要用变量保存参数值以便在调用程序中使用,则调用程序必须在执行存储过程时使用 OUTPUT 关键字。

示例

下列示例显示有一个输入参数和一个输出参数的存储过程。存储过程中的第一个参数 @title 将接收由调用程序指定的输入值,而第二个参数 @ytd_sales 将向调用程序返回该值。SELECT 语句使用 @title 参数以获得正确的 ytd_sales 值,并将该值赋予 @ytd_sales 输出参数。

 

CREATE PROCEDURE get_sales_for_title@title varchar(80),   -- This is the input parameter.@ytd_sales int OUTPUT -- This is the output parameter.AS  -- Get the sales for the specified title and -- assign it to the output parameter.SELECT @ytd_sales = ytd_salesFROM titlesWHERE title = @titleRETURNGO

 

 

 

下列程序用输入参数值执行存储过程,并将存储过程的输出值保存到调用程序的局部变量 @ytd_sales_for_title 中。

 

-- Declare the variable to receive the output value of the procedure.DECLARE @ytd_sales_for_title int-- Execute the procedure with a title_id value-- and save the output value in a variable.EXECUTE get_sales_for_title"Sushi, Anyone?", @ytd_sales = @ytd_sales_for_title OUTPUT -- Display the value returned by the procedure.PRINT 'Sales for "Sushi, Anyone?": ' +    convert(varchar(6),@ytd_sales_for_title)GOSales for "Sushi, Anyone?": 4095

执行存储过程时,也可为 OUTPUT 参数指定输入值。这样将允许存储过程从调用程序中接收一个值,更改该值或对该值执行操作,然后将新值返回至调用程序。在前面的示例中,可在执行存储过程前将一个值赋予 @ytd_sales_for_title 变量。@ytd_sales 变量在存储过程主体中包含参数值,而该存储过程在退出时,将 @ytd_sales 变量值返回至调用程序。这常常被称作"传址调用功能"。

 

如果在执行存储过程时对参数指定 OUTPUT,而在存储过程中该参数又不是用 OUTPUT 定义的,那么将收到一条错误信息。在执行带有 OUTPUT 参数的存储过程时,可以不指定 OUTPUT。这样不会返回错误,但将无法在调用程序中使用该输出值。