选择Top into Different Variables

时间:2013-10-23 15:18:57

标签: sql-server select

可能不可能,但我想我会问;

我想获取Top并将每个保存到另一个变量中。我知道有3个选择可以从Top 3获得第1,第2,第3,但我希望在一个声明中可能有可能吗?

Declare @Var1 as int,
Declare @Var2 as int,
Declare @Var3 as int
select Top 3 [SAVE 3 RETURNED RECORDS INTO VARIABLES] from Table

2 个答案:

答案 0 :(得分:6)

出于演示目的,您需要TOP 3 schema_id FROM sys.objects ORDER BY object_id

Declare @Var1 as int;
Declare @Var2 as int;
Declare @Var3 as int;


WITH T AS
(
SELECT *,
       ROW_NUMBER() OVER (ORDER BY object_id) RN
FROM sys.objects
)
SELECT @Var1 = MAX(CASE WHEN RN = 1 THEN schema_id END),
       @Var2 = MAX(CASE WHEN RN = 2 THEN schema_id END),
       @Var3 = MAX(CASE WHEN RN = 3 THEN schema_id END)
FROM T 
WHERE RN <= 3;

SELECT @Var1, @Var2, @Var3

它使用ROW_NUMBER对行进行编号,然后将它们转换为单行结果,用于分配变量。

答案 1 :(得分:3)

这是 another way

Declare @Var1 as int, @Var2 as int, @Var3 as int
Declare @rn int = 1

select top(3) @Var1 = case when @rn = 1 then val else @var1 end,
              @Var2 = case when @rn = 2 then val else @var2 end,
              @Var3 = case when @rn = 3 then val else @var3 end,
              @rn += 1 
from t
order by val

select @var1, @var2, @var3