在 DB2 中,如何声明一个变量以在函数内的多个声明的全局临时表中使用......?

In DB2, how can I declare a variable to use in multiple declared global temporary tables within the function..?

在 DB2 for i v7r3m0 中,我如何声明一个变量以用于同一函数中的多个声明的全局临时表..?

下面是我的代码示例。完整版有多个 DGTT,它们进行复杂的计算,然后在最后加入。我想如图所示定义变量 FIRSTDAY,但这会导致以下错误:

SQL Error [42618]: [SQL0312] Variable FIRSTDAY not defined or not usable.

这似乎是上下文问题;在 DGTT 定义的上下文中看不到该变量。如果这是一个独立的 SQL 脚本,我可以使用 DECLARE VARIABLE 并且它会起作用。此外,我当然可以多次复制 FIRSTDAY 的等式,但我宁愿不这样做。

CREATE OR REPLACE FUNCTION F_CERTOB.CertoNewPackageSheetsF1 ()
    RETURNS TABLE(  DAACCT  CHAR(5), 
                    DAIDAT  NUMERIC(8), 
                    DAINV   NUMERIC(15), 
                    QTY     NUMERIC(5)
                 )
    LANGUAGE SQL
    MODIFIES SQL DATA
    NOT DETERMINISTIC
    NO EXTERNAL ACTION
BEGIN

    DECLARE FIRSTDAY NUMERIC(8) DEFAULT 0 ;
    SET     FIRSTDAY = (YEAR(CURDATE() - 4 MONTHS) * 10000) + (MONTH(CURDATE() - 4 MONTHS) * 100) ;

    DECLARE GLOBAL TEMPORARY TABLE SESSION.NPS_DATA0 -- CREATE INITIAL MAIN DATA SET
        AS  (   SELECT  DAACCT          AS DAACCT,
                        DAIDAT          AS DAIDAT,
                        DAINV#          AS DAINV,
                        DAQTY           AS QTY
                FROM    F_CERTOB.DAILYT
                WHERE   DAIDAT = FIRSTDAY
--                WHERE   DAIDAT = 20190501 -- THIS WORKS
            )   WITH DATA WITH REPLACE ;

-- DGTT 2 also uses FIRSTDAY

-- DGTT 3 also uses FIRSTDAY

RETURN SELECT * FROM SESSION.NPS_DATA0 ;

END @

SELECT * FROM TABLE(F_CERTOB.CertoNewPackageSheetsF1()) @

DROP FUNCTION   F_CERTOB.CertoNewPackageSheetsF1() @
DROP TABLE      SESSION.NPS_DATA0 @

看来,在DDL语句中不允许使用变量。
尝试拆分 table 声明和数据插入步骤,如下所示:

DECLARE GLOBAL TEMPORARY TABLE SESSION.NPS_DATA0 -- CREATE INITIAL MAIN DATA SET
    AS  (   SELECT  DAACCT          AS DAACCT,
                    DAIDAT          AS DAIDAT,
                    DAINV#          AS DAINV,
                    DAQTY           AS QTY
            FROM    F_CERTOB.DAILYT
--          WHERE   DAIDAT = FIRSTDAY
            WHERE   DAIDAT = 20190501 -- THIS WORKS
        )   WITH NO DATA WITH REPLACE ;

INSERT INTO SESSION.NPS_DATA0
SELECT  DAACCT          AS DAACCT,
        DAIDAT          AS DAIDAT,
        DAINV#          AS DAINV,
        DAQTY           AS QTY
FROM    F_CERTOB.DAILYT
WHERE   DAIDAT = FIRSTDAY;