CREATE PROCEDURE DB2PAGINATION(IN ITBNAME VARCHAR(2000),-- 表名
IN ISHOWFIELD VARCHAR(1000),-- 顯示字段
IN IJOIN VARCHAR(1000),-- 聯接條件(如:內聯、外聯)
IN IWHERE VARCHAR(2000),-- 查詢條件(注意: 不要加WHERE)
IN IORDER VARCHAR(100),-- 排序條件(注意: 不要加ORDER BY)
IN IPAGESIZE INTEGER,-- 頁尺寸 如果為0 默認返回前一百萬條數據可以認為是返回所有數據
INOUT IOCURRENTPAGEIX INTEGER,-- 輸入和輸出:當前頁
OUT OPAGESTARTROW INTEGER,-- 輸出:當前開始行
OUT OPAGEENDROW INTEGER,-- 輸出:當前結束行
OUT OTOTALROWS INTEGER,-- 輸出:當前總記錄數
OUT OHASPREVIOUSPAGE INTEGER,-- 輸出:是否有上一頁
OUT OHASNEXTPAGE INTEGER,-- 輸出:是否有下一頁
OUT OTOTALPAGES INTEGER,-- 輸出:總頁數
OUT OERROR VARCHAR(1000))-- 輸出:錯誤信息
RESULT SETS 1
MODIFIES SQL DATA
NOT DETERMINISTIC
LANGUAGE SQL
BEGIN
/**//*----------------------------------------------------------------
* Copyright (C) 2007 Huacius
* 版權所有。
*
* 存儲過程分頁
*
*
//-----------------------------------------------------------------------*/
DECLARE STRSQL VARCHAR(6000);-- 主語句
DECLARE result CURSOR WITH RETURN TO CALLER FOR S2;
DECLARE exit handler FOR sqlexception-- 異常捕獲
BEGIN
set OERROR = 'error!'||strsql;
END;
-- BODY start --
if(iwhere <> '') then
set iwhere = ' where ' || iwhere;
end if;
if(iorder <> '') then
set iorder = 'order by ' || iorder;
end if;
if(ijoin <> '') then
set ijoin = ' ' || ijoin;
end if;
set strsql = 'select count(*) from ' || itbname || ijoin || iwhere;
prepare s2 from strsql;
open result;
fetch result into ototalrows;-- 總記錄數
close result;
if(ipagesize = 0) then
set ipagesize = 1000000;-- 每頁顯示數
end if;
set ototalpages = (ototalrows - 1) / ipagesize + 1;-- 總頁數
if(iocurrentpageix < 1) then
set iocurrentpageix = 1;-- 當前頁
else
if(iocurrentpageix > ototalpages) then
set iocurrentpageix = ototalpages;
end if;
end if;
set opagestartrow = ipagesize * (iocurrentpageix -1) + 1;-- 每頁開始數
if(iocurrentpageix = ototalpages) then
set opageendrow = ototalrows;-- 每頁結束數
else
set opageendrow = ipagesize * iocurrentpageix;
end if;
if(iocurrentpageix > 1) then
set ohaspreviouspage = 1;-- 是否有上一頁
else
set ohaspreviouspage = 0;
end if;
if(iocurrentpageix < ototalpages) then
set ohasnextpage = 1;-- 是否有下一頁
else
set ohasnextpage = 0;
end if;
set strsql = 'select * from (select rownumber() over(' || iorder || ') as rownum,'
|| ishowfield
|| ' from '
|| itbname
|| ijoin
|| iwhere
|| ') as temp where rownum between ' || rtrim(char(opagestartrow)) || ' and '
|| rtrim(char(opageendrow));
prepare s2 from strsql;
open result;
-- BODY end --
END
調用方法:
單表:
連接表: