存储列的总和,然后将其与触发器内的另一个表列相等(Oracle DBMS)

vulvrdjw  于 2023-04-29  发布在  Oracle
关注(0)|答案(1)|浏览(119)

我正在使用Oracle SQL Developer,但不能弄清楚如何实现我的任务。
下面是我的代码,它不能正常工作:

CREATE OR REPLACE TRIGGER TRIGGER1 
AFTER DELETE OR INSERT OR UPDATE OF AXLE, DIFERANTIAL, SHAFTS 
ON WAREHOUSE_PRODUCTS 
BEGIN
  
    SELECT 
        SUM(Shaft) AS shaftot,
        SUM(AXLE) AS axletot,
        SUM(diferantial) AS diftot 
    FROM 
        warehouse_products;

    UPDATE total_stocks
    SET shafts_stock = shafts_stock + shaftot,
        axle_stock = axle_stock + axletot,
        differential_stock = differential_stock + diftot
    WHERE 
        shafts_stock = shafts_stock 
        AND axle_stock = axle_stock 
        AND diferantial_stock = diferantial_stock;
END;

当指定的列受到插入、更新或删除影响时,我正在尝试将总和与另一个表列相等。

jjjwad0x

jjjwad0x1#

不要使用触发器,使用视图:

CREATE VIEW total_stocks (shafts_stock, axle_stock, diferantial_stock) AS
  SELECT SUM(Shaft),
         SUM(AXLE),
         SUM(diferantial)
  FROM   warehouse_products;

如果你必须使用触发器,那么你的total_stocks表应该只有一行,你可以将所有内容合并到一个MERGE语句中:

CREATE OR REPLACE TRIGGER TRIGGER1 
  AFTER DELETE OR INSERT OR UPDATE OF AXLE, DIFERANTIAL, SHAFT
  ON WAREHOUSE_PRODUCTS 
BEGIN
  MERGE INTO total_stocks dst
  USING (
    SELECT SUM(Shaft)       AS shafts_stock,
           SUM(AXLE)        AS axle_stock,
           SUM(diferantial) AS differential_stock
    FROM   warehouse_products
  ) src
  ON (1 = 1)
  WHEN MATCHED THEN
    UPDATE
    SET shafts_stock      = src.shafts_stock,
        axle_stock        = src.axle_stock,
        diferantial_stock = src.differential_stock
  WHEN NOT MATCHED THEN
    INSERT (shafts_stock, axle_stock, diferantial_stock)
    VALUES (src.shafts_stock, src.axle_stock, src.differential_stock);
END;
/

至于你的代码:

  • 在触发器规范中使用SHAFTS,在主体中使用SHAFT
  • 您有一个没有INTO子句的查询。
  • 您将新的总数添加到旧的总数中,因此您的库存水平将呈指数级增加,而不是显示总库存水平。库存水平下降的唯一方法是在其中一列中输入负值;这似乎是不正确的逻辑。

fiddle

相关问题