--
找出与某id相近的四条记录:
declare @tb table (id int ,cName char ( 10 ))
insert into @tb
select 3 , ' a ' UNION ALL
select 5 , ' b ' UNION ALL
select 6 , ' c ' UNION ALL
select 7 , ' d ' UNION ALL
select 10 , ' e ' UNION ALL
select 12 , ' g ' UNION ALL
select 13 , ' y ' UNION ALL
select 14 , ' i ' UNION ALL
select 15 , ' l ' UNION ALL
select 17 , ' w '
-- 设id=7,找出与7最相近的四条记录:5,6,7,10
-- ------------------------------------------------------
select top 4 * from @tb order by abs ( 7 - id)
/*
id cName
----------- ----------
7 d
6 c
5 b
10 e
(所影响的行数为 4 行)
*/
declare @tb table (id int ,cName char ( 10 ))
insert into @tb
select 3 , ' a ' UNION ALL
select 5 , ' b ' UNION ALL
select 6 , ' c ' UNION ALL
select 7 , ' d ' UNION ALL
select 10 , ' e ' UNION ALL
select 12 , ' g ' UNION ALL
select 13 , ' y ' UNION ALL
select 14 , ' i ' UNION ALL
select 15 , ' l ' UNION ALL
select 17 , ' w '
-- 设id=7,找出与7最相近的四条记录:5,6,7,10
-- ------------------------------------------------------
select top 4 * from @tb order by abs ( 7 - id)
/*
id cName
----------- ----------
7 d
6 c
5 b
10 e
(所影响的行数为 4 行)
*/
本文转自曾祥展博客园博客,原文链接:http://www.cnblogs.com/zengxiangzhan/archive/2010/01/03/1638178.html,如需转载请自行联系原作者