从另一个存储过程计算存储过程结果的最有效方法是什么?

时间:2008-09-17 04:03:38

标签: sql-server tsql

在存储过程中,我需要获取另一个存储过程的结果计数。具体来说,我需要知道它是否返回任何结果,或者是否为空集。

我可以创建一个临时表/表变量,将存储过程放入其中,然后对该数据运行select count。但我真的不关心数据本身,我需要的只是计数(或存在/不存在数据)。我想知道是否有更有效的方法来获取这些信息。

我不想只复制其他存储过程的内容并将其重写为选择计数。存储过程变化太频繁,无法使用。

9 个答案:

答案 0 :(得分:3)

那么,根据存储过程的工作方式,@@ ROWCOUNT会返回SP将执行的任何结果的#(包括更新): http://msdn.microsoft.com/en-us/library/ms187316.aspx

只有当您在sp中执行的最后一项操作将行返回到客户端时,这才会起作用...否则您将获得其他语句的结果。有意义吗?

答案 1 :(得分:1)

@@ ROWCOUNT

答案 2 :(得分:1)

使用out参数

答案 3 :(得分:1)

我认为你可以返回行数(使用RETURN)或使用out参数来获取值。

答案 4 :(得分:0)

如果您可以将其他过程重写为返回结果集的简单函数,则只需从中选择count(*)即可。

答案 5 :(得分:0)

似乎是其他人正在改变其他存储过程,无论这些过程发生什么变化,您都需要有效地检查结果。

创建一个诱饵表并将该过程的结果插入其中。

然后,您可以对结果执行行计数。如果我正确理解你的问题,它不是最有效但最可靠的解决方案。

Snipet:

DECLARE @res AS TABLE (
    [EmpID] [int] NOT NULL,
    [EmpName] [varchar](30) NULL,
    [MgrID] [int] NULL
)

INSERT @res 
EXEC dbo.ProcFoo

SELECT COUNT(*) FROM @res

答案 6 :(得分:0)

鉴于你真的不需要知道计数,只是你的sproc是否有数据,我建议这样:

CREATE PROCEDURE subProcedure @param1, @param2, @Param3 tinyint OUTPUT
AS
BEGIN
  IF EXISTS(SELECT * FROM table1 WHERE we have something to work with)
   BEGIN
    -- The body of your sproc
    SET @Param3 = 1
   END
  ELSE
   SET @Param3 = 0
END

现在你可以执行sproc并检查@Param3的值:

DECLARE @ThereWasData tinyint
exec subProcedure 'foo', 'bar', @ThereWasData OUTPUT
IF @ThereWasData = 1 
  PRINT 'subProcedure had data'
ELSE
  PRINT 'subProcedure had NO data'

答案 7 :(得分:0)

我认为你应该这样做:

Create  Procedure   [dbo].[GetResult]   (
    @RowCount   BigInt  =   -1  Output
)   As  Begin

    /*
        You can do whatever else you should do here.
    */

    Select  @RowCount   =   Count_Big(*)
        From    dbo.SomeLargeOrSmallTable
        Where   SomeColumn  =   'Somefilters'
        ;

    /*
        You can do whatever else you should do here.
    */

    --Reporting how your procedure has done the statements. It's just a sample to show you how to work with the procedures. There are many ways for doing these things.
    Return  @@Error;

End;

写完后你可以得到这样的输出结果:

Declare @RowCount   BigInt
,   @Result     Int
;

Execute @Result =   [dbo].[GetResult]   @RowCount   Out

Select  @RowCount
,   @Result
;

干杯

答案 8 :(得分:0)

  create proc test
    as
    begin
     select top 10 * from customers
    end
    go


    create proc test2 (@n int out)
    as
    begin
    exec test
    set @n = @@rowcount
    --print @n
    end
    go

    declare @n1 int =0

    exec test2 @n1 out
    print @n1
    --output result: 10
相关问题