使用 Sum 函数批量收集

Bulk Collect with Sum function

我正在尝试在 Oracle 数据库中使用 Bulk all 和 Forall:

程序原代码如下:

IF NVL(v_mc,0) != 0 THEN
        FOR rec IN
        (SELECT a.testid,
            SUM(pct * NVL(cap,0))/v_mc lead1
            BULK COLLECT INTO testids1, testids2
        FROM testtable a
        WHERE a.id      = n_id
        AND a.type      =n_type

        GROUP BY a.testid;
        )
        LOOP
            UPDATE testtable
            SET LEAD1    =ROUND(testids2(i),2)
            WHERE tid  = n_id
            AND type  = n_type
            AND testid   =testids1(i);
        END LOOP;
END IF;

所以在 select 语句中,我使用了 Sum 函数并且在这里也使用了别名。

我写的使用Bulk collect和Forall的代码如下:

PROCEDURE test
IS

    TYPE test1Tab IS TABLE OF sh_rpt_temp_peer_wip.test1%TYPE;
    TYPE test2Tab IS TABLE OF testtable.lead1%TYPE;
    testids1 testidTab; --Error 1 and Error 2
    testids2 LeadTab;

BEGIN

IF NVL(v_mc,0) != 0 THEN

     SELECT testid,
            SUM(pct * NVL(cap,0))/v_mc lead1
            BULK COLLECT INTO testids1, testids2
        FROM testtable a               --Error 3
        WHERE a.id      = n_id
        AND a.type      =n_type

        GROUP BY a.testid ORDER BY a.testid;

        FORALL i IN testids1.FIRST..testids1.LAST
          UPDATE testtable
            SET LEAD1    =ROUND(testids2(i),2)
            WHERE tid  = n_id  --Error 3
            AND type  = n_type
            AND testid   =testids1(i);

END IF;

END;

但是当我编译程序时,出现了多个错误。我对 PL/SQL 很陌生。请让我知道我是否可以在批量收集中将计算值作为列检索? 我在程序中遇到以下错误:

请告诉我这里有什么问题

谢谢

正如我发现您所引用的集合类型不在该过程的范围内,可能是您已全局声明。我修改了你的代码,试试看,希望对你有用。

PROCEDURE test
IS

    TYPE test1Tab IS TABLE OF testtable.testid%TYPE;
    TYPE test2Tab IS TABLE OF number;
    testids1 test1Tab; //Error 1 and Error 2
    testids2 test2Tab;

BEGIN

IF NVL(v_mc,0) != 0 THEN

     SELECT testid,
            SUM(pct * NVL(cap,0))/v_mc lead
            BULK COLLECT INTO testids1, testids2
        FROM testtable a               //Error 3
        WHERE a.id      = n_id
        AND a.type      =n_type
        GROUP BY a.testid ORDER BY a.testid;

        FORALL i IN testids1.FIRST..testids1.LAST
          UPDATE testtable
            SET LEAD    = ROUND(testids2(i),2)
            WHERE tid  = n_id   //Error 3
            AND type  = n_type
            AND testid   = testids1(i);

END IF;
END;