0

我有这个程序,它计算为汽车支付的总金额,并确定如果金额等于价格,汽车状态是否可以更改为“已售出”。

我知道问题是 car_payment 中的查询,但我找不到其他方法来计算金额的总和,有人可以帮我吗?

create or replace trigger tr_paid_car
    before insert
    or update of amount
    on car_payment
    for each row

declare 
    v_amount number;
    v_car_status_id car_status.car_status_id%type;
    v_price car.price%type;
begin
    select sum(amount)
        into v_amount
        from car_payment
        where car_id = :new.car_id;

    if inserting then 
        v_amount := v_amount + :new.amount;
    elsif updating then
        v_amount := v_amount + :new.amount - :old.amount;
    end if;

    select price
        into v_price
        from car
        where car_id = :new.car_id;

    if v_amount >= v_price then
        select car_status_id
        into v_car_status_id
        from car_status
        where description = 'SOLD';

        update car
            set car_status_id = v_car_status_id
            where car_id = :new.car_id;
    end if;
end;

/

4

1 回答 1

0

创建另一个名为:GET_CAR_PAY_AMT 的函数,如下所示。

CREATE OR REPLACE FUNCTION GET_CAR_PAY_AMT(p_car_id car_payment.car_id%type) return number
as
pragma autonomous_transaction;
x number;
begin
select sum(amount)
        into x
        from car_payment
        where car_id = p_car_id;
return x;
end GET_CAR_PAY_AMT;

现在使用函数 GET_CAR_PAY_AMT 代替触发器中的 SELECT 语句,如下所示:

替换下面的 SQL:

select sum(amount)
into v_amount
from car_payment
where car_id = :new.car_id;

和:

v_amount := GET_CAR_PAY_AMT(:new.car_id);
于 2018-05-10T16:20:47.333 回答