SQL Server获取表中中间连续的记录(不用where语句)

表pictures中有两个字段:id与title。id是自动编号的­

表中有5条记录:1--p1,2--p2,3--p3,4--p4,5--p5­

一、找到了一个小规律

string sqlstr = "select top 4 * from pictures order by id desc "; //查询结果p5,p4,p3,p2---说明是整个表先进行排序,再进行查询的­

string sqlstr = "select top 3 * from (select top 4 * from pictures order by id desc) "; //-------p5,p4,p3­

string sqlstr = "select top 3 * from (select top 4 * from pictures order by id desc) order by id desc";//-------p5,p4,p3

string sqlstr = "select top 3 * from (select top 4 * from pictures order by id desc) order by id asc"; //-------p2,p3,p4

二、获取单条记录:­

假设表中一共有counts条记录,现在想要查询第n条记录,则sql语句应是:­

select top 1 * from (select top (counts-n+1) * from pictures order by id desc) order by id asc­

第三条记录:­

string sqlstr = "select top 1 * from (select top 3 * from pictures order by id desc) order by id asc";//-------p3­

三、获取表中多条连续的记录­

假设表中一共有counts条记录,现在想要查询第n到第m条的记录,则sql语句应是:­

select top (m-n+1) * from (select top (counts-n+1) * from pictures order by id desc) order by id asc­

获取第二到第四条记录:­

string sqlstr = "select top 3 * from (select top 4 * from pictures order by id desc) order by id asc";//-------p2,p3,p4

 

转自:http://zshrong.blog.163.com/blog/static/184300254201142845055658/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值