SQL Server / T-SQL:从构造表返回单个值

时间:2018-07-30 13:26:51

标签: sql sql-server sql-server-2017

我正在编写一个内联函数,该函数接受固定数量的参数(在代码示例中为9),将这些参数排列到具有2列和4行的构造表中,对表进行排序,然后从中返回单个值所说的表(第1列中的值以及调用语句在第1-4行中的值)。

我已经完成了大部分工作。

但是我需要知道如何在最后选择特定的列和行索引。

您可能会问为什么我需要一个内联函数,答案是因为a)排序至关重要,b)内存优化表的计算列中使用了此排序,其中子查询是不允许,等等。

这是我到目前为止的代码:

CREATE FUNCTION [dbo].[SelectOrderedInputValue]
(
    -- 1-based row index of the desired return value
    @RequestedRowIndex INT,

    @InputValue1 INT,
    @InputValue2 INT,
    @InputValue3 INT,
    @InputValue4 INT,
    @InputRank1 INT,
    @InputRank2 INT,
    @InputRank3 INT,
    @InputRank4 INT
)
RETURNS TABLE AS RETURN
(
    /* Places the parameters into a table, and sorts by rank.

       I need to figure out how to specify a row and column,
       so I can return the single requested value from this table.

       In this case, I need to return the value in column #1 (alias InputValues)
       and row # @RequestedRowIndex*/

    SELECT TOP 4 InputValues FROM
    (VALUES
        ([InputValue1], [InputRank1]),
        ([InputValue2], [InputRank2]),
        ([InputValue3], [InputRank3]),
        ([InputValue4], [InputRank4])
    ) AS Inputs(InputValues, InputRanks) ORDER BY InputRanks ASC
)

2 个答案:

答案 0 :(得分:2)

无需为单个值返回表。只需使用标量函数:

CREATE FUNCTION [dbo].[SelectOrderedInputValue] (
    -- 1-based row index of the desired return value
    @RequestedRowIndex INT,

    @InputValue1 INT,
    @InputValue2 INT,
    @InputValue3 INT,
    @InputValue4 INT,
    @InputRank1 INT,
    @InputRank2 INT,
    @InputRank3 INT,
    @InputRank4 INT
) RETURNS INT AS
BEGIN
    /* Places the parameters into a table, and sorts by rank.

       I need to figure out how to specify a row and column,
       so I can return the single requested value from this table.

       In this case, I need to return the value in column #1 (alias InputValues)
       and row # @RequestedRowIndex*/
    DECLARE @retval INT;

    SET @retval = (SELECT TOP 4 *
                   FROM (VALUES ([InputValue1], [InputRank1]),
                                ([InputValue2], [InputRank2]),
                                ([InputValue3], [InputRank3]),
                                ([InputValue4], [InputRank4])
                        ) Inputs(InputValues, InputRanks)
                   ORDER BY InputRanks ASC
                   OFFSET @RequestedRowIndex-1 FETCH FIRST 1 ROW ONLY
                  );

    RETURN @retval;
END;

答案 1 :(得分:1)

尝试使用OFFSET FETCH

    DECLARE @RequestedRowIndex INT=4
    SELECT * FROM (
   SELECT TOP 4 * FROM
    (VALUES
        (10, 11),
        (20, 21),
        (30, 31),
        (40, 41)
    ) AS Inputs(InputValues, InputRanks) 
    ORDER BY InputRanks ASC )A 
    ORDER BY InputRanks ASC  
    OFFSET @RequestedRowIndex-1 ROWS FETCH NEXT 1 ROWS ONLY