表值函数 - 重复表声明

时间:2016-05-01 10:57:14

标签: sql sql-server

我在SQL Server中使用表值函数来返回带有关系的数据,或者在指定的某些条件下返回数据。

现在解决方案工作正常,但我不喜欢我必须两次声明表的事实 - 是否有任何workaroud?我可能不是插入@tmp表使用@ReturnTable,而是在函数结束时查询select top 1时必须删除该数据。

RETURNS @ReturnTable TABLE
    (
    idTable   INT,
    idOther   INT,
    name      VARCHAR(30)
    )
AS
     BEGIN
         DECLARE @tmp TABLE
            (   
            idTable         INT,
            idOther         INT,
            name            VARCHAR(30)
            )

         INSERT INTO @tmp
                SELECT idTable,
                       idOther,       
                       name
                FROM SomeTable

         IF (some condition)
             BEGIN
                 INSERT INTO @ReturnTable
                        SELECT TOP 1 WITH TIES idTable,
                                               idOther,       
                                               name
                        FROM @tmp
                        ORDER BY (some ordering)
             END;
         ELSE
             BEGIN
                 INSERT INTO @ReturnTable
                        SELECT TOP 1 idTable,
                                     idOther,       
                                     name
                        FROM @tmp
                        ORDER BY (some other ordering)
             END;
         RETURN;
     END;

1 个答案:

答案 0 :(得分:1)

尝试将您的功能重新编写为Inline table valued function

根据条件,您必须使用ROW_NUMBERDENSE_RANK窗口功能。使用TOP 1 with TIES

可以实现DENSE_RANK/RANK
RETURNS TABLE 
AS 
    RETURN 
      (SELECT idtable, 
              idother, 
              NAME 
       FROM   (SELECT CASE 
                        WHEN (some condition) THEN Dense_rank()OVER(ORDER BY (some ordering)) 
                        ELSE Row_number()OVER(ORDER BY (some other ordering)) 
                      END     AS RN, 
                      idtable,
                      idOther, 
                      NAME 
               FROM   sometable)a 
       WHERE  RN = 1)