3

I have a table which is not sorted by any of column. Is there any way to select next/previous record if I know only Id of current? (I'm using mssql)

Id     Label     Date
---------------------
1      label1    2011-01-10
7      label2    2011-01-15 -- how to get previous?
5      label3    2011-01-12 -- I know id of this record
10     label10   2011-01-25 -- how to get next?
12     label8    2011-01-13
2      label5    2011-01-29

Thanks in advance!

Vytalyi
  • 1,637
  • 3
  • 20
  • 33

3 Answers3

4

try this:

VALUES (1, 'label1', '2011-01-10'), (7, 'label2', '2011-01-15'),
       (5, 'label3', '2011-01-12'), (10, 'label10', '2011-01-25'),             
       (12, 'label8', '2011-01-13'), (2, 'label5', '2011-01-29')

select * from table007; 

Declare @inptID int=12;

;WITH CTE 
as
(
   select *, ROW_NUMBER() over (order by (select 0)) as rn 
   from table007
 )

select * 
from CTE 
where rn in( select rn-1 from CTE where id = @inptID)
union all
select * from CTE where rn in(select rn + 1 from CTE where id = @inptID);

SQL Fiddle Demo

DEMO

AnandPhadke
  • 13,160
  • 5
  • 26
  • 33
3

If it is not sorted by any column, there is no definitive next or previous record. Data in SQL Server has no order, other than that specified by an ORDER BY clause.

podiluska
  • 50,950
  • 7
  • 98
  • 104
  • As you said there will not be any order but as per my understanding when data gets stored in memory,it just appends to the last inserted row.So thats what OP also wants.I mean he wants to get previous and next row from heap. – AnandPhadke Sep 27 '12 at 13:19
2

If you really want the previous from the list you enclosed, here is a way.

declare @t table(Id int, Label varchar(10), Date date, s int identity(1,1))
insert @t (id, label, date) 
values(1,'label1','2011-01-10'),(7,'label2','2011-01-15'),
(5,'label3','2011-01-12'),(10,'label10','2011-01-25'),
(12,'label8','2011-01-13'),(2,'label5','2011-01-29')

--select the data with a self join

select t1.id as previous_id, t2.id, t2.Label, t2.Date, t3.id, t3.id as next_id
from @t t1
right join
@t t2 on t1.s + 1 = t2.s
left join
@t t3  on t2.s = t3.s - 1
t-clausen.dk
  • 43,517
  • 12
  • 59
  • 92
  • I'm not sure I got what is s column. I have no this coulmn in table. Do you want me to create it? – Vytalyi Sep 27 '12 at 12:56
  • Id, Label, Date are the columns. I don't want you to create new columns, I just want you to populate the temporary table with the data you have, then you can link the rows to the previous rows – t-clausen.dk Sep 27 '12 at 13:06
  • Well, it works for previous, thanks! And how I can modify this to see next and previous at the same time? – Vytalyi Sep 27 '12 at 13:47
  • @Vytalyi I now noticed you wanted both the next and the previous, so i modified my script to include both – t-clausen.dk Sep 28 '12 at 02:19
  • Yeah, looks like it works. Not a standard solution but I think I can do this until find something better. Thanks a lot! – Vytalyi Sep 28 '12 at 08:10