27,581
社区成员
发帖
与我相关
我的任务
分享
declare @table table(id int,name varchar(10))
insert into @table
select '8900','aaaa'union all
select '233','aaaa'union all
select '223','aaaa'union all
select '4','aaaa'
;with table1 as (select rowID=ROW_NUMBER() over(order by getdate()),* from @table)
select * from table1
where (select rowID from table1 where id=223) between rowID-1 and rowID+1
and rowID<>(select rowID from table1 where id=223)
=========================
rowID id name
-------------------- ----------- ----------
2 233 aaaa
4 4 aaaa
(2 行受影响)
;with cte as
(
select * ,rn=row_number()over(order by getdate()) from tb;
)
select *
from cte c join (
select rn from cte where col='特定值') b c.rn<>b.rn
where c.rn between b.rn-1 and b.rn+1create table #temp
(
id int,
col varchar(100)
)
insert #temp
select 1,'a' union all
select 4,'b' union all
select 7,'c' union all
select 9,'d' union ALL
select 10,'e'
SELECT * FROM #temp a
OUTER APPLY
(SELECT TOP(1) preid = id, precol = col FROM #temp WHERE id < a.id ORDER BY id DESC) b
OUTER APPLY
(SELECT TOP(1) nextid = id, nextcol = col FROM #temp WHERE id > a.id ORDER BY id) c
ORDER BY a.id
declare @table table (id int,col varchar(1))
insert into @table
select 1,'a' union all
select 4,'b' union all
select 7,'c' union all
select 9,'d'
--例如参数为4
DECLARE @i INT
SET @i=4
;WITH maco AS(select ROW_NUMBER() OVER (ORDER BY id) AS rowid,id, col from @table )
--得到下一条
select id,col FROM maco WHERE
rowid=(SELECT rowid+1 FROM maco WHERE id=@i)
/*
id col
----------- ----
7 c
*/
select top 1 * from tb where id<curent_id order by id desc --pre
select top 1 * from tb where id>curent_id order by id asc --next