我想将前 2 个结果存储在 2 个变量中。
创建表 t(id int); 插入 t (id) 值 (1),(2),(3),(4); 声明@id1 int 声明@id2 int 选择前 2 个 @id1 = 第一个 id, @id2 = 下一个 id 从T
SQLFiddle
我可以在一个查询中完成它而不使用循环吗?
我想将前 2 个结果存储在 2 个变量中。
创建表 t(id int); 插入 t (id) 值 (1),(2),(3),(4); 声明@id1 int 声明@id2 int 选择前 2 个 @id1 = 第一个 id, @id2 = 下一个 id 从T
我可以在一个查询中完成它而不使用循环吗?
declare @id1 int,@id2 int
;with cte as (
select top (2) id
from t
order by id
)
select @id1 = min(id), @id2 = max(id)
from cte
select @id1,@id2
with cte as (
select top 2 id, row_number() over(order by id) as rn
from t
order by id
)
select
@id1 = (select id from cte where rn = 1),
@id2 = (select id from cte where rn = 2)
或者
with cte as (
select top 2 id, row_number() over(order by id) as rn
from t
order by id
)
select
@id1 = max(case when rn = 1 then id end),
@id2 = max(case when rn = 2 then id end)
from cte
您可以LEAD()
用于 SQL Server 2012。
SELECT TOP 1 @id1 = ID, @id2 = LEAD(ID) OVER (ORDER BY ID) FROM t
使用两个 SELECT 很容易......
DECLARE @id1 INT
DECLARE @id2 INT
SELECT TOP 1 @id1 = x.id
FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY id) RN FROM t) x
WHERE x.RN = 1
SELECT TOP 1 @id2 = x.id
FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY id) RN FROM t) x
WHERE x.RN = 2
SELECT @id1, @id2
使用 SQL 2012,您显然可以
SELECT @id1 = id
FROM t ORDER BY id OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
SELECT @id2 = id
FROM t ORDER BY id OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY
或者即使在 2008 年,你也可以
; WITH Base AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY id) RN FROM t
)
SELECT @id1 = b1.id, @id2 = b2.id
FROM Base b1, Base b2
WHERE b1.RN = 1 AND B2.RN = 2
declare @id1 int
declare @id2 int
declare @table table(id int,rownum int)
insert into @table
select top 2 id,row_number() over( order by id) as rn from t
select @id1=case rownum when 1 then id else @id1 end,
@id2=case rownum when 2 then id end from @table
select @id1,@id2
2个选择更简单的方法:
declare @id1 int
declare @id2 int
select top 1 @id1 = id from t
select top 2 @id2 = id from t
select @id1, @id2