SQL插入前触发器

3
我正在尝试创建一个触发器,但在某个方面遇到了麻烦。我希望触发器能够检查插入的产品的库存水平,如果库存水平为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;
2个回答

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;

0
要提取哪个值? 要获取插入到销售表中的值,请使用

:new.fieldname


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接