assign variable a calculated value in pl/sql [message #610512] |
Thu, 20 March 2014 16:22 |
|
kevinb85
Messages: 6 Registered: March 2014 Location: Effingham, IL
|
Junior Member |
|
|
I have a created a code that uses the SUM function to calculate a value from other variables, but how do I assign my declared variable the value of that calculated value, keep getting errors. I want to declare "total" as the variable that should be assigned the value of the calculation of SUM(ol_quantity * inv_price). Without total assigned my variable "discount" won't have a basis to go off of. What should I insert and where?
SQL> DECLARE
2 total NUMBER(6,2);
3 discount NUMBER(7,3);
4 CURSOR c_cursor IS
5 SELECT orders.o_id, SUM(ol_quantity * inv_price)
6 FROM orders, order_line, inventory, item
7 WHERE orders.o_id = order_line.o_id
8 AND order_line.inv_id = inventory.inv_id
9 AND inventory.item_id = item.item_id
10 GROUP BY orders.o_id;
11 o_row c_cursor%ROWTYPE;
12 BEGIN
13 DBMS_OUTPUT.PUT_LINE('o_id' || CHR(9) || 'Total Order' || CHR(9) || CHR(9) || 'Discount');
14 DBMS_OUTPUT.PUT_LINE('----' || CHR(9) || '-----------' || CHR(9) || CHR(9) || '--------');
15 OPEN c_cursor;
16 LOOP
17 IF total > 100 AND total < 200
18 THEN discount := total * .1;
19 ELSIF total > 200
20 THEN discount := total * .2;
21 ELSE discount := 0;
22 END IF;
23 FETCH c_cursor INTO o_row;
24 EXIT WHEN c_cursor%NOTFOUND;
25 DBMS_OUTPUT.PUT_LINE(o_row.o_id || CHR(9) || total || CHR(9) || CHR(9) || discount);
26 END LOOP;
27 CLOSE c_cursor;
28 END;
29 /
o_id Total Order Discount
---- ----------- --------
1 0
6 0
2 0
5 0
4 0
3 0
PL/SQL procedure successfully completed.
|
|
|
|
|
|
|
|
|
|
|
|
|
Re: assign variable a calculated value in pl/sql [message #610559 is a reply to message #610532] |
Fri, 21 March 2014 04:13 |
cookiemonster
Messages: 13920 Registered: September 2008 Location: Rainy Manchester
|
Senior Member |
|
|
You should read up on for loops as well. This:
15 OPEN c_cursor;
16 LOOP
17 FETCH c_cursor INTO o_row;
18 EXIT WHEN c_cursor%NOTFOUND;
Can just be:
FOR o_row IN c_cursor LOOP
Then the close cursor statement can be removed along with the declaration of o_row (for loops declare record variables implicitly).
|
|
|
|