【问题标题】:trigger is not updating table触发器没有更新表
【发布时间】:2019-05-07 16:04:48
【问题描述】:

我创建了一个触发器,每当我更新不同表中的列时,它都会更新我创建的表。到目前为止,我的触发器已编译,但当我更新列时,触发器似乎没有触发或执行任何操作。
谁能帮帮我?


CREATE TABLE bb_sales_sum (
    idProduct number(2) NOT NULL,
    total number(6,2),
    quantity number); 


CREATE OR REPLACE TRIGGER BB_SALESUM_TRG
    AFTER UPDATE OF orderplaced on bb_basket 
    FOR EACH ROW
    WHEN (NEW.orderplaced = 1)
DECLARE 
    lv_count Number;
BEGIN   
    if :new.orderplaced = 1 then 
        for item in 
            (select idproduct, (quantity * price) AS total, quantity
            from bb_basketitem
            where idbasket = :old.idbasket)
    loop
        select count(*)
        into lv_count
        from bb_sales_sum where idProduct = item.idproduct;

        if lv_count = NULL then
            INSERT INTO bb_sales_sum
            VALUES (item.idproduct, item.total, item.quantity);
        else
            update bb_sales_sum 
            set quantity = item.quantity where
            idProduct = item.idproduct;
        end if;
    end loop;
    end if;

END; 
/
update bb_basket 
set orderplaced = 1 
where idbasket = 14;

select * from bb_sales_sum;

【问题讨论】:

  • my answer 对您之前对同一问题提出的问题有什么问题?你试过了吗?请注意,if lv_count = NULL 永远不会是真的。 count(*) 始终返回 0 或实际计数。此外,即使是真的,something = NULL 也不是比较 null 的正确方法
  • 我对合并一点也不熟悉。想知道是否有其他方法可以做到这一点?
  • 我非常感谢您的帮助。

标签: oracle plsql


【解决方案1】:

您可以使用类似的 MERGE 语句,使用来自 bb_basketitem 的值,而不是 for 循环。

CREATE OR REPLACE TRIGGER BB_SALESUM_TRG
  AFTER UPDATE OF orderplaced on bb_basket 
    FOR EACH ROW 
 WHEN (NEW.orderplaced = 1)
BEGIN   
   MERGE INTO bb_sales_sum t USING 
      (  select idproduct, (quantity * price) AS total, quantity
                    from bb_basketitem item
                        where idbasket = :old.idbasket 
         ) s  
         ON (s.idproduct = t.idproduct ) 
             WHEN MATCHED THEN UPDATE
                SET  quantity  = s.quantity
              WHEN NOT MATCHED THEN
         INSERT (
              idproduct,quantity,total)
         VALUES
              ( s.idproduct,s.quantity,s.total );          

END; 
/

DEMO

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多