2010-01-18 48 views
0

这里是表 和类似的数据:要上线和下线的数据进行特定的ID

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

从以上数据我要像 数据如果我通过了id作为参数和返回从数据从向上和由顺序袍

例如,如果我传递id作为参数= 4,则它应该是返回 上线2行和下行2行为特定的ID,并且它应该是这样的

 
id name 

2 test2 
3 test3 
4 test4 
5 test5 
6 test6 

和同为ID = 3

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

回答

1

SELECT TOP 3 ID,名称 FROM表 WHERE ID = < @id ORDER BY ID DESC

UNION 

SELECT TOP 2 id, name 
FROM table 
WHERE id > @id 
ORDER BY id ACS 
+0

假设'id'是一个主键,可能最好在这里使用'UNION ALL'。 – RedFilter 2010-01-18 14:57:09

+0

是的,它在工作 – Paresh 2010-01-18 14:58:59

+0

你好,我已经尝试过上面的脚本。因为联盟和秩序是不一起工作的。 – Paresh 2010-01-19 10:35:48