SQL分页语句三方案
方法一:
SELECT TOP 页大小 * FROM table1 WHERE id NOT IN ( SELECT TOP 页大小*(页数-1) id FROM table1 ORDER BY id ) ORDER BY id
方法二:
SELECT TOP 页大小 * FROM table1 WHERE id > ( SELECT ISNULL(MAX(id),0) FROM ( SELECT TOP 页大小*(页数-1) id FROM table1 ORDER BY id ) A ) ORDER BY id
方法二倒序:
SELECT TOP 页大小 * FROM table1 WHERE ID <= ( SELECT ISNULL(MIN(ID),(SELECT MAX(ID) FROM table1 )) FROM ( SELECT TOP (页大小*(页数-1)) ID FROM tbl_files ORDER BY ID DESC ) A ) ORDER BY ID DESC
方法三:
SELECT TOP 页大小 * FROM ( SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* FROM table1 ) A WHERE RowNumber > 页大小*(页数-1)
分页方案二:(利用ID大于多少和SELECT TOP分页)效率最高,需要拼接SQL语句
分页方案一:(利用Not In和SELECT TOP分页) 效率次之,需要拼接SQL语句
分页方案三:(利用SQL的游标存储过程分页) 效率最差,但是最为通用
例子:
以下轉載至http://www.cnblogs.com/zcttxs/archive/2012/04/01/2429151.html
2.几种典型的分页sql,下面例子是每页50条,198*50=9900,取第199页数据。
1 1:row_number() over() 2 select top 50 * from ( 3 select Row_Number() over(order by id) as rownumber ,* from table)a 4 where rownumber >9900 5 6 select * from ( 7 select row_number() over(order by id)as rownumber,*from table)a 8 where rownumber >9000 adn rownuber<9951 9 10 2 not in 11 12 select top 50 * from table 13 where id not in (select top 9900 id from table order by id) 14 order by id
1 2 3 ALTER PROCEDURE 存儲過程名 4 ( 5 6 @tbName VARCHAR(255), --表名 7 @tbGetFields VARCHAR(1000)= '*',--返回字段 8 @OrderfldName VARCHAR(255), --排序的字段名 9 @PageSize INT=20, --页尺寸 10 @PageIndex INT=1, --页码 11 @OrderType bit = 0, --0升序,非0降序 12 @strWhere VARCHAR(1000)='', --查询条件 13 --@TotalCount INT OUTPUT --返回总记 14 15 ) 16 AS 17 18 BEGIN 19 DECLARE @strSql VARCHAR(5000) --主语句 20 DECLARE @strSqlCount NVARCHAR(500)--查询记录总数主语句 21 DECLARE @strOrder VARCHAR(300) -- 排序类型 22 IF ISNULL(@strWhere,'')<>'' 23 set @strSqlCount='select @TotalCout=count(*) from '+@tbName+' 24 where 1=1'+@strWhere 25 else set @strSqlCount='select @TotalCount=count(*) from '+@tbName 26 27 28 ------分頁 29 IF @PageIndex <=0 set @PageIndex =1 30 IF(@OrderType<>0) set @strOrder='ORDER BY'+@OrderfldName+'DESC' 31 ELSE SET @strOrder=' ORDER by'+@OrderfldName+' ASC' 32 33 SET @strSql='SELECT * FROM 34 (SELECT ROW_NUMBER() OVER('+@strOrder+') RowNo,'+@tbGetFields+'FROM'+@tbName +' WHERE 1=1'+@strWhere+')tb 35 where tb.RowNo between '+str((@PageIndex-1)*PageSize+1)+'AND' 36 +str(@PageIndex * @PageSize) 37 38 exec(@strSql) 39 select @TotalCount 40 end 41 42 43
111111