2014-01-31 73 views
0

SP定义与返回参数需要返回参数的存储过程

if OBJECT_ID('CountSeatleEmployee') is not null 
drop proc CountSeatleEmployee 

go 

CREATE PROC CountSeatleEmployee 
AS 
DECLARE @Total int 
SELECT @Total =Count(*) 
from [AdventureWorks2012].[Person].[Person] P 
WHERE P.EMAILPROMOTION =0 
RETURN @Total 

--Execute SP 
declare @Count int 
exec @Count = CountSeatleEmployee 
SELECT @COUNT 
--11158 Records 

--same SP without Return Parameter 

if OBJECT_ID('CountSeatleEmployee') is not null 
drop proc CountSeatleEmployee 
go 
CREATE PROC CountSeatleEmployee 
AS 
SELECT Count(*) 
from [AdventureWorks2012].[Person].[Person] P 
WHERE P.EMAILPROMOTION =0 

exec CountSeatleEmployee' 

现在为什么不直接使用以下。这两个提供相同的输出。为什么我们种子返回参数

回答

0

单向提供返回变量中的信息,然后通过选择变量将另一个数据集或记录集转换为记录集。它取决于你想要使用哪一个应用程序。

if OBJECT_ID('CountSeatleEmployee') is not null 
drop proc CountSeatleEmployee 

go 

CREATE PROC CountSeatleEmployee 
AS 
DECLARE @Total int 
SELECT @Total =Count(*) 
from [AdventureWorks2012].[Person].[Person] P 
WHERE P.EMAILPROMOTION =0 


Select * from [AdventureWorks2012].[Person].[Person] P 
WHERE P.EMAILPROMOTION =0 
RETURN @Total 

--Execute SP 
declare @Count int 
exec @Count = CountSeatleEmployee --This will return the recordset of the table and returns the total rows into the variable @Count 
SELECT @COUNT 
1

根据我的经验,返回值通常用于错误条件。并非每个人都有相同的经历。

RETURN语句仅限于返回一个整数,所以它的用处有一定的限制(在我看来)。我更喜欢第二种方法,因为它可以使代码更加一致。想象一下你想要一个名字而不是一个计数,你将无法使用return语句。另一方面,有些人更喜欢第一种使用return语句的方法(无论哪里都可以这样做)。理由是它是一种优化技术。当您从前端调用第一个代码示例时,不需要处理该过程并期望它会返回结果集。相反,它只是从数据库传回的单个4字节值。第二个例子需要在前端进行更多的处理,因为一个过程可以返回各种各样的东西。它可以返回多个结果集,每个结果集可以包含多列和多行。您的前端代码需要评估返回的数据,然后构建处理数据的适当结构。这需要额外的CPU周期。

我不一定会推荐一个,我只是想解释的理由。