程式包頭
create or replace package PCK_Pager is type T_Curor is ref Cursor; Procedure GetRecordByPage ( p_tableName in varchar2, --表名 p_strWhere in out varchar2, --查詢條件 p_orderColumn in varchar2, --排序的列(如:ID desc,Name asc) p_curPage in out Number, --當前頁 p_pageSize in out Number, --每頁顯示記錄條數 p_fields in varchar2, --要查詢的列 p_totalRecords out Number, --總記錄數 p_totalPages out Number, --總頁數 v_cur out T_Curor --返回的結果集 );end PCK_Pager;
程式包體:
create or replace package body PCK_Pager isPROCEDURE GetRecordByPage (p_tableName in varchar2, --表名 p_strWhere in out varchar2, --查詢條件 p_orderColumn in varchar2, --排序的列(如:ID desc,Name asc) p_curPage in out Number, --當前頁 p_pageSize in out Number, --每頁顯示記錄條數 p_fields in varchar2, --要查詢的列 p_totalRecords out Number, --總記錄數 p_totalPages out Number, --總頁數 v_cur out T_Curor) --返回的結果集IS v_sql VARCHAR2(8000) := ''; --sql語句 v_startRecord Number(4); --開始顯示的記錄條數 v_endRecord Number(4); --結束顯示的記錄條數BEGIN -- 條件的轉換 if instr(lower(trim(p_strWhere)),'and ') <> 1 then p_strWhere := ' and ' || p_strWhere; end if; --記錄中總記錄條數 v_sql := 'SELECT TO_NUMBER(COUNT(*)) FROM ' || p_tableName || ' where (1=1) '; IF p_strWhere IS NOT NULL or p_strWhere <> '' THEN v_sql := v_sql || p_strWhere; END IF; EXECUTE IMMEDIATE v_sql INTO p_totalRecords; --驗證頁面記錄大小 IF p_pageSize < 0 THEN p_pageSize := 0; END IF; --根據頁大小計算總頁數 IF MOD(p_totalRecords, p_pageSize) = 0 THEN p_totalPages := trunc(p_totalRecords / p_pageSize); ELSE p_totalPages := trunc(p_totalRecords / p_pageSize) + 1; END IF; --驗證頁號 IF p_curPage < 1 THEN p_curPage := 1; END IF; IF p_curPage > p_totalPages THEN p_curPage := p_totalPages; END IF; --實現分頁查詢 v_startRecord := (p_curPage - 1) * p_pageSize + 1; v_endRecord := p_curPage * p_pageSize; v_sql := 'SELECT * FROM (SELECT A.*, rownum r FROM ' || '(SELECT '|| p_fields ||' FROM ' || p_tableName; IF p_strWhere IS NOT NULL or p_strWhere <> '' THEN v_sql := v_sql || ' WHERE (1=1) ' || p_strWhere; END IF; IF p_orderColumn IS NOT NULL or p_orderColumn <> '' THEN if instr(lower(p_orderColumn),'order by ') = 0 then v_sql := v_sql || ' order by ' || p_orderColumn || ' '; else v_sql := v_sql || ' ' || p_orderColumn || ' '; end if; END IF; v_sql := v_sql || ') A WHERE rownum <= ' || v_endRecord || ') B WHERE r >= ' || v_startRecord; DBMS_OUTPUT.put_line(v_sql); OPEN v_cur FOR v_sql;END GetRecordByPage;end PCK_Pager;