以下是Oracle存储过程分页查询返回数据集的方法:
CREATE OR REPLACE PROCEDURE PROC_GET_DATA_PAGING(P_TABLENAME IN VARCHAR2, –表(视图)名
P_STRWHERE IN VARCHAR2, –查询条件
P_ORDERCOLUMN IN VARCHAR2, –排序的列
P_CURPAGE IN OUT NUMBER, –当前页
P_PAGESIZE IN OUT NUMBER, –每页显示记录条数
P_TOTALRECORDS OUT NUMBER, –总记录数
P_TOTALPAGES OUT NUMBER, –总页数
V_CUR OUT TYPES.CURSORTYPE) –返回的结果集
IS
V_SQL VARCHAR2(4000) := ”; –SQL语句
V_STARTRECORD NUMBER(10); –开始显示的记录条数
V_ENDRECORD NUMBER(10); –结束显示的记录条数
V_SHOWALL INTEGER; –是否显示全部记录
BEGIN
–记录中总记录条数
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
V_SHOWALL := 1;
P_PAGESIZE := 0;
END IF;
IF V_SHOWALL IS NULL THEN
–根据页大小计算总页数
IF MOD(P_TOTALRECORDS, P_PAGESIZE) = 0 THEN
P_TOTALPAGES := TRUNC(P_TOTALRECORDS / P_PAGESIZE, 0);
ELSE
P_TOTALPAGES := TRUNC(P_TOTALRECORDS / P_PAGESIZE, 0) + 1;
END IF;
ELSE
P_TOTALPAGES := 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 * 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
V_SQL := V_SQL || ‘ ORDER BY ‘ || P_ORDERCOLUMN;
END IF;
IF V_SHOWALL IS NULL THEN
V_SQL := V_SQL || ‘) A WHERE ROWNUM <= ' || V_ENDRECORD ||
‘) B WHERE R >= ‘ || V_STARTRECORD;
ELSE
V_SQL := V_SQL || ‘) A ) B ‘;
END IF;
DBMS_OUTPUT.PUT_LINE(V_SQL);
OPEN V_CUR FOR V_SQL;
END PROC_GET_DATA_PAGING;
,