有谁知道吗???

fangxianghua9801 2005-10-09 09:27:35
在MSSQL中假设已知当前记录ID,那如何获取当前记录的上一条记录和下一条记录????
...全文
71 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
fangxianghua9801 2005-10-09
  • 打赏
  • 举报
回复
是的虎虎兄说的对"id的间隔不一定就是1"
zsforever 2005-10-09
  • 打赏
  • 举报
回复
楼上没有考虑断号的情况,而且id的间隔不一定就是1
zlp321002 2005-10-09
  • 打赏
  • 举报
回复
--测试环境
declare @t table( id int ,name varchar(10))
insert into @t select 1,'小明'
union all select 2,'小华'
union all select 3,'小平'

--借用临时表
select identity(int,1,1) as IDS ,* into # from @t
--上一条记录
select * from @t where id=(select id from @t where Name='小华')-1

--下一条记录
select * from @t where id=(select id from @t where Name='小华')+1
--删除临时表
drop table #
--结果
id name
----------- ----------
1 小明

(所影响的行数为 1 行)

id name
----------- ----------
3 小平

(所影响的行数为 1 行)
QQMagicer 2005-10-09
  • 打赏
  • 举报
回复
----取前一条记录
select top 1 * from tb1
where ID < 已知ID
order by ID desc

--取后一条记录
select top 1 * from tb1
where ID > 已知ID
order by ID asc

fangxianghua9801 2005-10-09
  • 打赏
  • 举报
回复
id是主键
fangxianghua9801 2005-10-09
  • 打赏
  • 举报
回复
就是比如:
ID NAME
1 小明
2 小华
3 小平
现在,我已知"小华"并知道其ID为"2",我想实现:取得小华前面的那条记录是小明,小华后面的那条记录是小平
zsforever 2005-10-09
  • 打赏
  • 举报
回复
如果ID是主键
那么
select * from your table where id = (select max(id) from yourtable where id < ID)
select * from your table where id = (select min(id) from yourtable where id > ID)
就是你要的记录
fangxianghua9801 2005-10-09
  • 打赏
  • 举报
回复
顶,谢谢??请教了
churchatp1 2005-10-09
  • 打赏
  • 举报
回复
不是很明白你得问题,可以详细一点不?

34,576

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧