首页 > 代码库 > sqlserver获取当前id的前一条数据和后一条数据
sqlserver获取当前id的前一条数据和后一条数据
一、条件字段为数值的情况
select
*
from
tb
where
id=@id;
--当前记录
select
top
1 *
from
tb
where
id>@id
order
by
id;
--下一条记录
select
top
1 *
from
tb
where
id<@id
order
by
id
desc
--上一条记录
二、以排序的思路出发的一种方案
;
WITH
TUsers
AS
(
SELECT
*, ROW_NUMBER() OVER (
ORDER
BY
vcUserID)
AS
_ROW
FROM
DB_Fast_Users.dbo.T_Users
AS
A(NOLOCK)
)
SELECT
*
into
#T
FROM
TUsers
-- 上一条
select
B.*
from
#T
AS
A(NOLOCK)
left
join
#T
AS
B(NOLOCK)
ON
B._ROW = (A._ROW - 1)
where
A.vcUserID=
‘Test1‘
-- 下一条
select
B.*
from
#T
AS
A(NOLOCK)
left
join
#T
AS
B(NOLOCK)
ON
B._ROW = (A._ROW + 1)
where
A.vcUserID=
‘Test1‘
drop
table
#T
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。