Question

I have 3 tables:

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

and orders (order_id, order_date, cust_id, emp, id).
Basically Im trying to create a function that gets the total order cost when the order_id is input but Im am having trouble trying to put it into code.
Specifically trying to put each product into a separate variable.

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;
/
Was it helpful?

Solution

It sounds like you just want a 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;

There doesn't appear to be any need to do the COUNT or to introduce a loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top