0

我正在尝试创建一个触发器TrgDisAmount来读取PROD_NAMEPRICEPRODUCT表中读取和计算DISCOUNTAMOUNTSALES插入的每个新行的SERIALand值PCODE

这些是表格信息

Table SALES (SERIAL, PCODE, PROD_NAME, PRICE, DISCOUNT, AMOUNT)

Table PRODUCT (PCODE, PROD_NAME, PROD_CAT, PRICE)

Table DISCOUNT (PROD_CAT, DISCOUNT_RATE)

笔记:

  1. 输入SERIALPCODEonly 的值,其余列应TrgDisAmount仅由触发器输入
  2. 获取DISCOUNT_RATE使用函数GetDiscount

我已经创建了从 tableGetDiscount获取的函数。DISCOUNT_RATEDISCOUNT

这是我的尝试:

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用来到达特定的列。这样做合法吗?


示例输出应如下所示:

SQL> insert into sales values (1,'MB-101',null, null, null, null);

Result in SALES table:
   SERIAL : 1,
   PCODE : MB-101,
   PROD_NAME : IPHONE 6+,
   PRICE : 250 ,
   DISCOUNT : 25,
   AMOUNT : 225
4

2 回答 2

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。但是,这是您问题中的算术,您没有提供任何示例数据来建议任何其他方法。

于 2015-06-20T12:26:17.503 回答
0

您可以尝试更改调用函数的方式吗?

正如 Gordon 所说,在这种情况下不应使用 :old

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);

在此处输入图像描述

于 2015-06-20T19:48:03.593 回答