可能不可能,但我想我会问;
我想获取Top
并将每个保存到不同的变量中。我知道可以进行 3 次选择并从中选择第 1、第 2、第 3,Top 3
但我希望它可能在一个语句中?
IE
Declare @Var1 as int,
Declare @Var2 as int,
Declare @Var3 as int
select Top 3 [SAVE 3 RETURNED RECORDS INTO VARIABLES] from Table
可能不可能,但我想我会问;
我想获取Top
并将每个保存到不同的变量中。我知道可以进行 3 次选择并从中选择第 1、第 2、第 3,Top 3
但我希望它可能在一个语句中?
IE
Declare @Var1 as int,
Declare @Var2 as int,
Declare @Var3 as int
select Top 3 [SAVE 3 RETURNED RECORDS INTO VARIABLES] from Table
假设出于演示目的,您想要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
对行进行编号,然后将它们转换为用于分配给变量的单行结果。
这是另一种方式:
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