当行不存在时更新触发器

时间:2013-08-26 08:28:01

标签: sql oracle plsql triggers oracle11g

我有两张桌子 的OrderItems:

"ORDER_ITEMS_CODE" VARCHAR2(20) NOT NULL ENABLE, 
"ORDER_CODE" VARCHAR2(20) NOT NULL ENABLE, 
"ITEM_CODE_ORDERS" VARCHAR2(20) NOT NULL ENABLE, 
"ORDER_QUANTITY" NUMBER(4,0) NOT NULL ENABLE, 
"ORDER_UNIT" VARCHAR2(5) NOT NULL ENABLE, 
"UNIT_PRICE" NUMBER(38,5), 
"ORDERED_IN" VARCHAR2(6), 
"OR_QUANTITY_TON" NUMBER(38,5),
"Warehouse_CODE" VARCHAR2(20) NOT NULL ENABLE

另一张表是库存:

"INVENTORY_CODE" VARCHAR2(20) NOT NULL ENABLE, 
"ITEM_CODE" VARCHAR2(20) NOT NULL ENABLE, 
"WAREHOUSE_CODE" VARCHAR2(20),  
"IN_Q_TON" NUMBER(38,5), 
"OR_Q_TON" NUMBER(38,5) 

我创建了一个触发器来计算“OR_QUANTITY_TON”= Sum(“OR_QN_TON”)

create or replace trigger sum_Or_IT
after insert or update or delete on orderitems
begin
    update INVENTORY set OR_Q_TON = (
        select sum(or_quantity_ton) from orderitems 
        where
        orderitems.item_code_orders = INVENTORY.item_code
        and
        warehouse_code = '1');
end;

这是一个库存表,OR_Q_TON列是每个项目的订购数量的总和,但如果订单中不存在项目,我希望订单数量为零。 如果“Orderitems”表中不存在“item_code_orders”,那么我想要例外,然后OR_Q_TON = 0

我尝试了这个,但它没有用,我得到了( - )不是(0)

EXCEPTION
  WHEN NO_DATA_FOUND THEN
    update INVENTORY set OR_Q_TON = 0 ;

3 个答案:

答案 0 :(得分:0)

它不是一个例外,在上面的更新的情况下,oracle不会引发异常 您需要使用sql%rowcount

TRY:

IF SQL%ROWCOUNT = 0 THEN
  update INVENTORY set OR_Q_TON = 0 ;
END IF;

答案 1 :(得分:0)

您可以使用此而不是使用EXCEPTION,

IF SQL%NOTFOUND THEN 
    UPDATE inventory SET or_q_ton = 0 ;
    COMMIT;
END IF;

答案 2 :(得分:0)

触发器应为

create or replace trigger sum_Or_IT
after insert or update or delete  on orderitems
begin
    update INVENTORY set OR_Q_TON = (
        select coalesce(sum(or_quantity_ton),0) from orderitems 
        where
        orderitems.item_code_orders = INVENTORY.item_code
        and
        warehouse_code = '1')        
end;

通过使用coalesce函数而不是异常来解决问题