sql - 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
)
解决方案
无需为单个值返回表。只需使用标量函数:
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;
推荐阅读
- mysql - 连接到远程 MySQL 的 Excel VBA 中的错误处理
- php - 有没有办法只显示总和的一行,目前它显示两行作为输出
- python - 在实数数组中找到最近元素的最快方法
- html - 包装时如何制作不同大小的弹性项目以填充父项
- android - 仅点击一个通知时删除了所有通知
- sql - 选择查询中的重复行
- azure-active-directory - 通过 Microsoft graph SDK\API 将用户添加到 Azure Active Directory 中的目录角色
- ubuntu - 无法创建主目录。这很可能是权限问题
- magento2 - 如果 crontab 早于服务器 cron,则何时执行 cron 文件
- android - 使用远程电话调试应用程序