views:

22

answers:

1

here is the table and data like:

id name
1  test1
2  test2
3  test3
4  test4
5  test5
6  test6

From above data i want the data like if i pass the id as parameter and return the data from from up and gown by order

Example if i pass the id as parameter = 4 then it should be return upline 2 row and downline 2 row for particular id, and it should be like this

id name

2  test2
3  test3
4  test4
5  test5
6  test6

and same for the id = 3

id name
1  test1
2  test2
3  test3
4  test4
5  test5

+1  A: 

Hi,

SELECT TOP 3 id, name
FROM table
WHERE id =< @id 
ORDER BY id DESC

UNION 

SELECT TOP 2 id, name
FROM table
WHERE id > @id 
ORDER BY id ACS
IordanTanev
Assuming `id` is a primary key, probably best to use `UNION ALL` here.
RedFilter
Yes, it is working
Paresh
Hello, I have tried with above script. because Union and order by is not working together.
Paresh
So can you provide me alternative solution
Paresh
Yes my mistake i just wrote that by hand i did not test it here are two alternatives SELECT *FROM ( SELECT TOP 3 id, name FROM table WHERE id =< @id ORDER BY id DESC) xUNION SELECT *FROM ( SELECT TOP 2 id, name FROM table WHERE id > @id ORDER BY id ACS) xSecond alternativeSELECT TOP 3 id, nameINTO #tmpFROM tableWHERE id =< @id ORDER BY id DESCINSERT INTO #tmpSELECT TOP 2 id, nameFROM tableWHERE id > @id ORDER BY id ACSSELECT * FROM #tmpDROP TABLE #tmp
IordanTanev