首页 > 解决方案 > SQL Server / T-SQL:从构造的表中返回单个值

问题描述

我正在编写一个内联函数,它接受固定数量的参数(代码示例中为 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
)

标签: sqlsql-serversql-server-2017

解决方案


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

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;

推荐阅读