表:SUBSCRIPTION
C_ID SUB_YEAR SUB_AMOUNT DISCOUNT PAID_AMOUNT
----------------------------------------------------
1 1 1250 0 0
2 2 2520 0 0
3 8 1459 0 0
4 6 7456 0 0
5 1 2584 0 0
6 3 2578 0 0
7 4 5478 0 0
8 5 5000 0 0
我需要的查询是,
运行查询后,应使用值填充discount和paid_amount列。
我的查询是:
BEGIN
FOR REC IN(SELECT SUB_YEAR FROM SUBSCRIPTION)
LOOP
IF(REC.SUB_YEAR>1 AND REC.SUB_YEAR<=2) THEN
UPDATE SUBSCRIPTION
SET DISCOUNT = 10,P_AMOUNT= SUB_AMOUNT-SUB_AMOUNT*.1;
ELSIF(REC.SUB_YEAR>2 AND REC.SUB_YEAR<=3) THEN
UPDATE SUBSCRIPTION
SET DISCOUNT = 20,P_AMOUNT= SUB_AMOUNT-SUB_AMOUNT*.2;
ELSIF(REC.SUB_YEAR>3) THEN
UPDATE SUBSCRIPTION
SET DISCOUNT = 25,P_AMOUNT= SUB_AMOUNT-SUB_AMOUNT*.25;
ELSE
UPDATE SUBSCRIPTION
SET DISCOUNT = 0,P_AMOUNT= SUB_AMOUNT;
END IF;
END LOOP;
IF SQL%NOTFOUND THEN
Dbms_output.put_line('No Employee Selected');
ElsIF SQl%FOUND THEN
Dbms_output.put_line('Employee Selected');
END IF;
END;
问题出在所有行上,discount
列填充了25%,paid_amount
填充了sub_amount 25%的折扣。
答案 0 :(得分:2)
您在查询中错过了WHERE
条款,
BEGIN
FOR REC IN(SELECT SUB_YEAR FROM SUBSCRIPTION)
LOOP
IF(REC.SUB_YEAR>1 AND REC.SUB_YEAR<=2) THEN
UPDATE SUBSCRIPTION
SET DISCOUNT = 10,p_amount= SUB_AMOUNT-SUB_AMOUNT*.1
WHERE sub_year >1 and sub_year <= 2
ELSIF(REC.SUB_YEAR>2 AND REC.SUB_YEAR<=3) THEN
UPDATE SUBSCRIPTION
SET DISCOUNT = 20,p_amount= SUB_AMOUNT-SUB_AMOUNT*.2
WHERE SUB_YEAR>2 AND SUB_YEAR<=3;
ELSIF(REC.SUB_YEAR>3) THEN
UPDATE SUBSCRIPTION
SET DISCOUNT = 25,p_amount= SUB_AMOUNT-SUB_AMOUNT*.25
WHERE SUB_YEAR > 3
ELSE
UPDATE SUBSCRIPTION
SET DISCOUNT = 0,p_amount = SUB_AMOUNT
WHERE <condition>;
END IF;
END LOOP;
END;
或者您可以使用简单的UPDATE
查询
UPDATE subscription
set discount = CASE WHEN sub_year >1 and sub_year <= 2 THEN 10
WHEN sub_year >2 and sub_year <= 3 THEN 20
WHEN sub_year >3 THEN 25
ELSE 0 END,
p_amount = CASE WHEN sub_year >1 and sub_year <= 2 THEN SUB_AMOUNT-SUB_AMOUNT*.1
WHEN sub_year >2 and sub_year <= 3 THEN SUB_AMOUNT-SUB_AMOUNT*.2
WHEN sub_year >3 THEN SUB_AMOUNT-SUB_AMOUNT*.25
ELSE SUB_AMOUNT END;