sqlserver 查询数据分页,类似mysql的limit0,20

来源:互联网 发布:怎么在知乎回答问题 编辑:程序博客网 时间:2024/06/09 23:17

项目最近使用sqlserver2008,以前都是mysql,习惯用limit了,可惜sqlserver不支持。。。

1. 网上的很多使用top

查询第X页,每页Y条记录

最基本的处理方法(原理):

如果表中有主键(记录不重复的字段也可以),可以用类似下面的方法,当然y,(x-1)*y要换成具体的数字,不能用变量:
select top y * from 表 where 主键 not in(select top (x-1)*y 主键 from 表)


如果表中无主键,可以用临时表,加标识字段解决.这里的x,y可以用变量.

select id=identity(int,1,1),*  into #tb from 表
select * from #tb where id between (x-1)*y and x*y-1


2.还有使用 row_number() over() 这个也是我目前使用的

select * from ( select row_number() over( order by id desc ,time desc ,a desc ) as rownum, id,time,a,b,c,d from table where a=1 and b=0  ) as t where rownum>0 and rownum<=20

注意 子查询的的order by 是在 select row_number() over( order by id desc ,time desc ,a desc ) as rownum 这里面 ,不要跟在 where 条件后面


原创粉丝点击