使用DB2數據庫的過程中,存儲過程是一定會遇到的問題,本文將為您詳細解疑DB2數據庫中翻頁存儲過程,供您參考,希望能對您有所啟迪。
CREATE PROCEDURE KYJT.USP_A_FY(IN PTBLNAME VARCHAR(1000), --表名
IN PSHOWNAME VARCHAR(1000), -- 需要顯示字段名
IN PFLDNAME VARCHAR(1000), --字段名(主表主鍵,不可重復)
IN PPAGESIZE INTEGER, -- 頁尺寸 如果為0 默認返回前一千萬條數據 可以認為是返回所有數據
IN PPAGEINDEX INTEGER,--頁碼
IN PORDERTYPE INTEGER, --設置排序類型, 非 0 值則降序(按主鍵排序)
IN PSTRWHERE VARCHAR(1000) --查詢條件 (注意: 不要加 WHERE)
)
MODIFIES SQL DATA
DETERMINISTIC
LANGUAGE SQL
BEGIN
/**//*----------------------------------------------------------------
* Copyright (C) 2006 笑瘋
* 版權所有。
*
* 過程功能描述:
* 多功能通用翻頁查詢語句(DB2)
*
* 創建標識:[email protected](2006-5-1修改)
*
//-----------------------------------------------------------------------*/
DECLARE C_STRSQL VARCHAR(6000); -- 主語句
DECLARE C_STRTMP VARCHAR(100); -- 臨時變量
DECLARE C_STRORDER VARCHAR(400); -- 排序類型
DECLARE bill_task CURSOR WITH RETURN TO CALLER FOR S1;
--SET PSHOWNAME = PSHOWNAME || ',' || PFLDNAME;
IF (PPAGEINDEX=0) THEN
SET PPAGEINDEX = 1;
END IF;
IF (PPAGESIZE=0) THEN
SET PPAGESIZE = 10000000;
END IF;
-- 設置排序規則
IF (PORDERTYPE<>0) THEN
SET C_STRTMP = '<(SELECT MIN';
SET C_STRORDER = ' ORDER BY ' || PFLDNAME || ' DESC';
ELSE
SET C_STRTMP = '>(SELECT MAX';
SET C_STRORDER = ' ORDER BY ' || PFLDNAME || ' ASC';
END IF;
--
SET C_STRSQL = 'SELECT ' || PSHOWNAME || ' FROM '|| PTBLNAME || ' WHERE ' || PFLDNAME || ' ' || C_STRTMP || '( '|| 'TBLTMP.TTT ) FROM (SELECT ' || PFLDNAME || ' AS TTT FROM ' || PTBLNAME || ' ' || C_STRORDER || ' FETCH FIRST ' || CHAR((PPAGEINDEX-1)*PPAGESIZE) || ' ROWS ONLY) AS TBLTMP)' || C_STRORDER || ' FETCH FIRST ' || CHAR(PPAGESIZE) || ' ROWS ONLY';
--
IF (PSTRWHERE <> '') THEN
SET C_STRSQL = 'SELECT ' || PSHOWNAME || ' FROM '|| PTBLNAME || ' WHERE ' || PFLDNAME || ' ' || C_STRTMP || '( '|| 'TBLTMP.TTT ) FROM (SELECT ' || PFLDNAME || ' AS TTT FROM ' || PTBLNAME || ' WHERE ' || PSTRWHERE || ' '|| C_STRORDER || ' FETCH FIRST ' || CHAR((PPAGEINDEX-1)*PPAGESIZE) || ' ROWS ONLY) AS TBLTMP) AND ' || PSTRWHERE || ' ' || C_STRORDER || ' FETCH FIRST ' || CHAR(PPAGESIZE) || ' ROWS ONLY';
END IF;
--
IF (PPAGEINDEX=1) THEN
SET C_STRTMP = '';
IF (PSTRWHERE <> '') THEN
SET C_STRTMP = ' WHERE ' || PSTRWHERE;
END IF;
SET C_STRSQL = 'SELECT ' || PSHOWNAME || ' FROM '|| PTBLNAME || ' ' || C_STRTMP || ' ' || C_STRORDER || ' FETCH FIRST ' || CHAR(PPAGESIZE) || ' ROWS ONLY';
END IF;
PREPARE S1 FROM C_STRSQL;
--OPEN C_STRSQL;
--EXECUTE S1;
OPEN bill_task;
END