SQL计算表值函数中临时表的总行数

时间:2014-04-03 14:11:23

标签: sql-server function count table-valued-parameters

如果@t等于1,我需要在@total中插入的总行数。

我该怎么做?

ALTER FUNCTION [dbo].[myfunction]
(   
    @ID int = NULL,
    @years int = NULL,
   ,@total BIT = 0 
)
RETURNS @t TABLE (
    RowNum int,
    ID int,
    years int,
) 
AS
BEGIN
    INSERT INTO @t
       SELECT  
          ROW_NUMBER() OVER(ORDER BY years) AS RowNum,
          ID,
          years,
       FROM dbo.mytable
       WHERE ..     

    RETURN 
END

结果的外观应该是:

Total   RowNum   ID   year
-------------------------------------
  3       1      101  2014
  3       2      102  2015
  3       3      103  2016 

谢谢!

1 个答案:

答案 0 :(得分:1)

RETURNS @t TABLE (
    Total int,
    RowNum int,
    ID int,
    years int,
) 

...

INSERT INTO @t
       SELECT  
          NULL,
          ROW_NUMBER() OVER(ORDER BY years) AS RowNum,
          ID,
          years,
       FROM dbo.mytable
       WHERE ..

...
IF(@total=1) BEGIN
    DECLARE @Count INT
    SELECT @Count=COUNT(*) FROM @t
    UPDATE @t SET Total=@Count
END
RETURN