SELECT INTO返回多于1行 - ORA-01422

时间:2013-04-27 11:58:23

标签: oracle plsql select-into ora-01422

我有3张桌子:

products (prod_id, prod_name, prod_sale_price), order_details (order_id, prod_id, prod_quantity) 

orders (order_id, order_date, cust_id, emp, id)
基本上我试图创建一个函数,在输入order_id时获得总订单成本,但我在尝试将其放入代码时遇到了麻烦。
特别试图将每个产品放入一个单独的变量中。

CREATE OR REPLACE FUNCTION TotalOrderCost (input_id IN NUMBER)
RETURN NUMBER
IS

    given_id NUMBER := input_id;
    prod_count NUMBER;
    prod_id NUMBER;
    prod_price_by_quantity NUMBER := 0;
    total_order_cost NUMBER := 0;

BEGIN

    SELECT  COUNT(prod_id)
    INTO    prod_count
    FROM    order_details
    WHERE   order_id = given_id;

    FOR i IN 1..prod_count
        LOOP

            /* select into that returns more then 1 row when there is more than one product in the order*/
            SELECT  prod_sale_price*prod_quantity
            INTO    prod_price_by_quantity
            FROM    order_details od
                JOIN products p
                    ON od.prod_id = p.prod_id
            WHERE   order_id = given_id;

            total_order_cost := total_order_cost + prod_price_by_quantity;

        END LOOP;

    RETURN total_order_cost;

END TotalOrderCost;
/

1 个答案:

答案 0 :(得分:1)

听起来你只想要SUM

SELECT  SUM(prod_sale_price*prod_quantity)
  INTO  total_order_cost 
  FROM    order_details od
     JOIN products p
       ON od.prod_id = p.prod_id
 WHERE   order_id = given_id;

似乎没有必要进行COUNT或引入循环。