0

我有 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;
/
4

1 回答 1

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;

似乎不需要执行COUNTor 引入循环。

于 2013-04-27T12:02:40.083 回答