将值返回到存储过程中的查询变量

时间:2014-02-11 18:32:21

标签: sql sql-server-2008 tsql stored-procedures

我有一个看起来像这样的存储过程:

CREATE PROCEDURE dbo.Distribute 
    -- Add the parameters for the stored procedure here
    DECLARE @COMPANYID VARCHAR(MAX);
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    --Determine who has the large queue
    SELECT TOP 1 COMPANYID, COUNT(COMPANYID) AS 'Count', WorkerName
    FROM   TABLE
    WHERE  WorkerName IN ( 'Jimmy', 'Sally' )
    AND COMPANYID = @COMPANYID
    GROUP  BY COMPANYID, WorkerName
    ORDER BY COUNT(COMPANYID) DESC

    RETURN

END
GO

我想将返回值放入变量中,以便我可以在存储过程中进一步向下做更多的逻辑?

需要将workerName返回给我需要用于其他内容的变量。

2 个答案:

答案 0 :(得分:4)

这不是您问题的直接答案,但如果您的所有存储过程都应该检索顶行并将其中一列作为输出参数返回,那么将其转换为内联表可能会做得更好 - 有价值的功能:

-- of course, you need to DROP PROCEDURE dbo.name
-- prior to creating a function by the same name
CREATE FUNCTION dbo.Distribute
    @COMPANYID VARCHAR(MAX)
RETURNS TABLE
AS
RETURN
    --Determine who has the large queue
    SELECT TOP 1 COMPANYID, COUNT(COMPANYID) AS [Count], WorkerName
    FROM   TABLE
    WHERE  WorkerName IN ( 'Jimmy', 'Sally' )
    AND COMPANYID = @COMPANYID
    GROUP  BY COMPANYID, WorkerName
    ORDER BY COUNT(COMPANYID) DESC
;

这将为您提供各种情况下的灵活性。例如,您可以按原样返回行:

SELECT * FROM dbo.Distribute(...);

或将其插入表格中:

INSERT INTO dbo.SomeTargetTable (...)
SELECT ... FROM dbo.Distribute(...);

或者,如果在目前情况下,您需要将WorkName的值存储到变量中,则可以执行以下操作:

SELECT @WorkName = WorkName FROM dbo.Distribute(...);

此外,您可以返回参数的结果(并在同一查询中使用它们):

SELECT ...
FROM dbo.SomeTable AS t
CROSS APPLY dbo.Distribute(t.ArgumentColumn) AS d
WHERE d.WorkerName = ...  -- for an example
;

使用存储过程也可以实现类似的灵活性,尽管编码更多。您可以将结果作为输出参数和行返回。您仍然无法直接在查询中使用SP的结果,与等效的内联TVF的结果相同。

作为最后一点,我想强调,为了达到最佳效果,该功能应该是内联 TVF,而不是多语句 TVF。当在复杂查询中“看到”前者时,查询规划器可以(并且确实)将函数的主体与查询的其余部分混合在一起,这使得规划人员能够提出可能的最佳执行计划。

答案 1 :(得分:2)

尝试将其变为变量:

declare @WorkerName as varchar(max)

select
     @WorkerName = WorkerName
from (
   SELECT TOP 1 COMPANYID, COUNT(COMPANYID) AS 'Count', WorkerName
   FROM   TABLE
   WHERE  WorkerName IN ( 'Jimmy', 'Sally' )
   AND COMPANYID = @COMPANYID
   GROUP  BY COMPANYID, WorkerName
   ORDER BY COUNT(COMPANYID) DESC
) _Worker

从这里开始,您可以在程序中使用它,使用返回值更改为函数,或使用输出参数将其发送回调用者。