我尝试创建触发器TrgDisAmount
以从PROD_NAME
表中读取PRICE
和PRODUCT
并计算DISCOUNT
和{{插入了AMOUNT
和SALES
值的每个新行的SERIAL
表的{}}。
这些是表格信息
PCODE
注意:
Table SALES (SERIAL, PCODE, PROD_NAME, PRICE, DISCOUNT, AMOUNT)
Table PRODUCT (PCODE, PROD_NAME, PROD_CAT, PRICE)
Table DISCOUNT (PROD_CAT, DISCOUNT_RATE)
和SERIAL
的值,其余列应仅由触发器PCODE
输入TrgDisAmount
获取DISCOUNT_RATE
。我已经创建了GetDiscount
函数来从表GetDiscount
获取DISCOUNT_RATE
。
这是我的尝试:
DISCOUNT
当我运行该块时,它会向我显示此错误:
create or replace trigger TrgDisAmount
before insert on SALES for each row
begin
if :new.PCODE = :old.PRODUCT.PCODE then
:new.PROD_NAME := :old.PRODUCT.PROD_NAME;
:new.PRICE := :old.PRODUCT.PRICE;
:new.DISCOUNT := :old.product.PRICE / (GetDiscount(:old.PRODUCT.PROD_CAT));
:new.AMOUNT := :new.PRICE - :new.DISCOUNT;
end if;
insert into SALES columns (PROD_NAME, PRICE, DISCOUNT, AMOUNT)
values (:new.PROD_NAME, :new.PRICE, :new.DISCOUNT, :new.AMOUNT);
end;
/
我使用PLS-00049: bad bind variable 'OLD.PRODUCT'
来访问特定列。这样做是否合法?
示例输出应该是这样的:
Table_Name.Column_name
答案 0 :(得分:1)
在插入触发器之前创建时,只需设置:new
值。您实际上并未插入表中。这是处理的下一步。
此外,在insert
触发器中,仅引用:new
值,而不是:old
。没有:old
值,这是您获得的具体错误。
然后,您需要执行查询以从其他表中获取相关信息。结果应如下所示:
create or replace trigger TrgDisAmount
before insert on SALES
for each row
begin
select p.price / d.discount into :new.discount
from product p join
discount d
on p.prod_cat = d.prod_cat
where :new.pcode = p.pcode;
:new.AMOUNT := :new.PRICE - :new.DISCOUNT;
end;
定义折扣的算法看起来非常可疑。使用此方法,10%的折扣将表示为1.11。但是,这是您的问题中的算术,并且您没有提供样本数据来建议任何其他方法。
答案 1 :(得分:0)
您可以尝试更改您调用函数的方式。
戈登提到:在这种情况下不应该使用旧的
CREATE or replace trigger TrgDisAmount
Before insert
on SALES
for each row
DECLARE
v_prod_cat varchar2(20);
BEGIN
select PROD_NAME into :NEW.PROD_NAME
from PRODUCT
where PRODUCT.PCODE = :NEW.PCODE;
select PRICE into :NEW.PRICE
from PRODUCT
where PRODUCT.PCODE = :NEW.PCODE;
select PROD_CAT into v_prod_cat from discount where PROD_CAT
in( select PROD_CAT from PRODUCT where PCODE = :NEW.PCODE);
select GetDiscount(v_prod_cat) into :NEW.discount from dual;
:new.AMOUNT := :new.PRICE - :new.DISCOUNT;
END;
/
Trigger created.
SQL> show err;
No errors.
insert into sales values(701,1,NULL,NULL,NULL,NULL);