create or replace package AutoPagenation is
-- Author : MARK
-- Created : 2010-12-30 11:23:18
-- Purpose :
-- Public type declarations
-- 返回结果集的游标
TYPE typeCousor IS REF CURSOR;
-- 分页的存储过程
procedure PageNation(
tblName in varchar2, --查询的表名
strFields in varchar2,--查询的字段
strSortedField IN varchar2,--排序的字段
sortType IN NUMBER,--排序的类型,1为DESC,默认为ASC
pageSize IN NUMBER,--分页的容量,默认为20条/页
pageIndex IN NUMBER,--要取的页码,默认为第1页
strWhere IN varchar2,--查询条件,不要写Where
recordCount OUT VARCHAR2,--输出值,记录总数
PageCount OUT NUMBER,--输出值,页总数
selRecords OUT typeCousor
);
end AutoPagenation;
create or replace package body AutoPagenation is
PROCEDURE PageNation(
tblName in varchar2, --查询的表名
strFields in varchar2,--查询的字段
strSortedField IN varchar2,--排序的字段
sortType IN NUMBER,--排序的类型,1为DESC,默认为ASC
pageSize IN NUMBER,--分页的容量,默认为20条/页
pageIndex IN NUMBER,--要取的页码,默认为第1页
strWhere IN VARCHAR2,--查询条件,不要写Where
recordCount OUT VARCHAR2,--输出值,记录总数
PageCount OUT NUMBER,--输出值,页总数
selRecords OUT typeCousor --输出的结果集
) is
tmpSortType VARCHAR2(10);
tmpPageSize NUMBER;
tmpPageIndex NUMBER;
tmpStrSqlCount VARCHAR2(500);
tmpStrSql VARCHAR2(500);
tmpStrRecodSql varchar2(500);
startPageDataIndex NUMBER;
endPageDataIndex NUMBER;
tmpPageCount NUMBER;
begin
--排序的类型
IF sortType = 1 THEN
tmpSortType := ' DESC';
ELSE
tmpSortType := ' ASC';
END IF;
--分页容量
IF pageSize IS NULL OR pageSize = 0 THEN
tmpPageSize := 20;
ELSE
tmpPageSize := pageSize;
END IF;
--要取的页码
IF pageIndex IS NULL OR pageIndex = 0 THEN
tmpPageIndex := 1;
ELSE
tmpPageIndex := pageIndex;
END IF;
--查询记录
IF strWhere IS NULL OR strWhere = ' ' THEN
BEGIN
tmpStrSqlCount := 'SELECT COUNT(*) FROM '||tblName;
IF strFields = '*' THEN
tmpStrSql := 'SELECT t.* from '||tblName||' t order by '||strSortedField||tmpSortType;
ELSE
tmpStrSql := 'SELECT '||strFields||' from '||tblName||' order by '||strSortedField||tmpSortType;
END IF;
END;
ELSE
BEGIN
tmpStrSqlCount := 'SELECT COUNT(*) FROM '||tblName||' where '||strWhere;
IF strFields = '*' THEN
tmpStrSql := 'SELECT t.* from '||tblName||' t where '||strWhere||' order by '||strSortedField||tmpSortType;
ELSE
tmpStrSql := 'SELECT '||strFields||' from '||tblName||' where '||strWhere||' order by '||strSortedField||tmpSortType;
END IF;
END;
END IF;
--
EXECUTE IMMEDIATE tmpStrSqlCount INTO recordCount;
--- 定义始终页码的数据位置
startPageDataIndex := tmpPageSize* ( tmpPageIndex -1)+1;
endPageDataIndex := tmpPageIndex * tmpPageSize;
---求页总数
tmpPageCount := mod(recordCount,tmpPageSize);--求余运算
IF tmpPageCount >0 THEN
tmpPageCount := 1;
ELSE
tmpPageCount := 0;
END IF;
tmpPageCount := TRUNC(recordCount/tmpPageSize) +tmpPageCount;
PageCount := tmpPageCount;
--取出页码定义的结果集
tmpStrRecodSql := 'SELECT * FROM (SELECT ROWNUM rowno,tmp.* FROM ('||tmpStrSql||') tmp where ROWNUM
<='||endPageDataIndex|| ') where rowno >= '||startPageDataIndex;
OPEN selRecords FOR tmpStrRecodSql;
end PageNation;
end AutoPagenation;