【问题标题】:SQL before insert trigger插入触发器之前的 SQL
【发布时间】:2015-12-16 19:55:22
【问题描述】:

我正在尝试创建触发器,但在某个方面遇到了麻烦。我想要触发器做的是检查正在插入的产品的库存水平,如果库存水平 = 0,那么触发器将阻止插入,如果水平在两个值之间,它将允许插入但显示警告,最后如果级别高于某个值,它将不插入任何问题。

我的问题是从插入中提取信息以获得触发变量@stock_level 的正确值。

下面我有一个示例插入语句,该语句将从 GUI 中检索,下面是我计划使用的触发器。我已手动将所需信息输入到触发器中,但是否可以在不硬编码值的情况下提取此信息?

插入声明

  --sample insert
  insert into sales_table values (1,2,3,4, '12/31/2015', '12:30:21');

触发器

  create or replace trigger inv_check
  before insert on SALES_TABLE
  --declaring variable that contains the stock number of the product being inserted
  --4 is the product code and 1 is the outlet_number taken from the above
  DECLARE @stock_level = (select quantity from inventory_table where product_code = 4 and outlet_number = 1);
  BEGIN

  IF @stock_level = 0 then
    DBMS_OUTPUT.PUT_LINE("Sorry, out of stock");
    ROLLBACK;
  ELSIF @stock_level > 0 and @stcok_level < 15 then
    DBMS_OUTPUT.PUT_LINE("Running low order more");
    --continue with insert
  ELSE
    DBMS_OUTPUT.PUT_LINE("Inserting row...");
  END;

【问题讨论】:

    标签: mysql sql triggers


    【解决方案1】:

    您根本不需要声明变量。在这种情况下,您尝试分配给变量的值存储在 :new.stock_level 中,触发器就是这种情况。这是您发布的代码的修复

    CREATE OR REPLACE TRIGGER inv_check
    BEFORE INSERT ON sales_table
    BEGIN
        IF :new.stock_level == 0 THEN 
            DBMS_OUTPUT.PUT_LINE("Sorry, out of stock");
            ROLLBACK;
        ELSE IF :new.stock_level > 0 AND :new.stock_level < 15 THEN
            DBMS_OUTPUT.PUT_LINE("Running low order more");
            --continue with insert
        ELSE
            DBMS_OUTPUT.PUT_LINE("Inserting row...");
        END IF;
    END;
    

    【讨论】:

      【解决方案2】:

      您需要提取什么价值? 要获取在 sales_table 中插入的值,请使用

      :new.fieldname

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-24
        • 1970-01-01
        相关资源
        最近更新 更多