尽管在 table 中声明了列 'quantity',但遇到 "PLS-00302: component 'QUANTITY' must be declared"

encountering "PLS-00302: component 'QUANTITY' must be declared" although the column 'quantity' is declared in the table

我试图遍历游标以获取一些值,我的方法类似于 this answer。并且代码如下:

SET SERVEROUTPUT ON;

DECLARE
    sold_phone_id Sale.phone_id%TYPE;
    sold_count number;

BEGIN
    FOR row IN (
                SELECT Sale.phone_id, SUM(Sale.quantity)
                FROM Sale
                GROUP BY Sale.phone_id
            )
    LOOP
        sold_phone_id := row.phone_id;
        sold_count := row.quantity;
        DBMS_OUTPUT.PUT_LINE(sold_phone_id || ' ' || sold_count);
    END LOOP;


END;
/ 

但是,我遇到了以下错误:

 sold_count := row.quantity;
                                  *
ERROR at line 13:
ORA-06550: line 13, column 21:
PLS-00302: component 'QUANTITY' must be declared
ORA-06550: line 13, column 3:
PL/SQL: Statement ignored

我已通过以下方式宣布我的销售 table:

CREATE TABLE Sale(
    id number,
    phone_id number,
    quantity number,
    sale_date date,
    seller_id number,
    PRIMARY KEY(id),
    FOREIGN KEY(seller_id) REFERENCES Seller(id)
);

您的子查询没有 return 此列。为 sum():

使用别名
BEGIN
    FOR row IN (
                SELECT phone_id, SUM(quantity) as quantity   --> here
                FROM Sale
                GROUP BY Sale.phone_id
            )
    LOOP
        sold_phone_id := row.phone_id;
        sold_count := row.quantity;
        DBMS_OUTPUT.PUT_LINE(sold_phone_id || ' ' || sold_count);
    END LOOP;
END;
/

在for循环查询中使用以下代码部分: SUM(Sale.quantity) 作为临时变量

然后在第 15 行使用 row.TEMPVARIABLE 代替 row.quantity