Oracle分页
①.rownum分页(分三步走) ROWNUM只是反应记录在结果集中的位置,并不反应排序后的位置 (效率次之)
a. select a.*,rownum rn from (select * from emp) a;
b. select * from (select a.*,rownum rn from (select * from emp) a where rownum<=10);
c. select * from (select * from (select a.*,rownum rn from (select * from emp) a where rownum<=10) where rn >=6);
如果只需要查询指定列,只需修改最里层的子查询
select * from (select * from (select a.*,rownum rn from (select ename,sal from emp) a where rownum<=10) where rn >=6);
如果要排序的话,只需修改最里层的子查询。
select * from (select * from (select a.*,rownum rn from (select ename,sal from emp order by sal) a where rownum<=10) where rn >=6);
② 分析函数来分 row_number() 而排序函数ROW_NUMBER()反应的是排序后的位置。(效率最差)
SELECT * FROM ( SELECT ROW_NUMBER() OVER( ORDER BY SAL ) IDX , EMPNO , ENAME , SAL FROM EMP ) WHERE IDX BETWEEN 6 AND 10 ;
pageSzie : 每页显示的记录数
pageNow : 当前的页数
SELECT * FROM ( SELECT ROW_NUMBER() OVER( ORDER BY SAL ) IDX , EMPNO , ENAME , SAL FROM EMP ) WHERE IDX BETWEEN (pageSize*(pageNow-1)+1) AND pageSize*pageNow ;
③ 根据ROWID分页(效率最佳)但不容易理解
6.编写分页的存储过程
具体要求:编写一个存储过程,要求可以输入表名,每页显示记录数、当前页。返回总记录数、总页数、和返回的结果集。
select * from (select a.*,rownum rn from (select * from emp) a where rownum>=1) where rn <=6;
首先创建一个包,早包中定义一个引用游标
create or replace package mypackage as
type mycur is ref cursor;
end mypackage;
--编写分页的存储过程
create or replace procedure paging
(tableName in varchar2,--表名
pageSize in number, --每页显示的记录数
pageNow in number, --当前页
myRows out number, --总记录数
myPageCount out number,--总页数
myCursor out mypackage.mycur --返回的记录集
)
is
--定义sql语句
v_sqlString varchar2(1000);
--定义两个整数
v_begin number := (pageNow-1)*pageSize+1;
v_end number := pageNow*pageSize;
begin
v_sqlString := 'select * from (select a.*,rownum rn from (select * from '||tableName||') a where rownum<='||v_end||') where rn >='||v_begin;
--将游标与sql进行关联
open myCursor for v_sqlString;
--计算出myRows和myPageCount
v_sqlString := 'select count(*) from '||tableName;
--执行sql语句,将返回值赋给myRows
execute immediate v_sqlString into myRows;
--计算myPageCount
if mod(myRows,pageSize)=0 then --myRows%pageSize=0不能这样写 Oracle中没有%操作符
myPageCount := myRows/pageSize;
else
myPageCount := myRows/pageSize+1;
end if;
--关闭游标
--close myCursor; --这句不能要,执行时会出现Cursor is Closed错误
end;