[英]SQL before insert trigger
I am trying to create a trigger but I'm running into trouble on a certain aspect. 我试图创建一个触发器,但我在某个方面遇到了麻烦。 What I want the trigger to do is check the stock levels of a product being inserted, if the stock levels = 0 then the trigger will prevent the insert, if the level is between two values it will allow the insert but display a warning and lastly if the level is above a value it will insert no questions asked. 我想要触发器检查正在插入的产品的库存水平,如果库存水平= 0则触发器将阻止插入,如果水平在两个值之间,它将允许插入但显示警告,最后如果级别高于某个值,则不会插入任何问题。
My problem is extracting the information from the insert in order to obtain the correct value for the trigger variable @stock_level
. 我的问题是从插入中提取信息,以获得触发变量@stock_level
的正确值。
Below I have a sample insert statement that will be retrieved from a GUI and below is the trigger I plan on using. 下面我有一个示例插入语句,将从GUI中检索,下面是我计划使用的触发器。 I have entered in the required information into the trigger by hand but is it possible to extract this information without hard coding in the values? 我已手动将所需信息输入到触发器中,但是可以在没有硬编码的情况下提取此信息吗?
Insert Statement 插入声明
--sample insert
insert into sales_table values (1,2,3,4, '12/31/2015', '12:30:21');
Trigger 触发
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;
You don't need to declare the variable at all. 您根本不需要声明变量。 In this case, the value you tried to assign to the variable is stored in :new.stock_level, such is the case with triggers. 在这种情况下,您尝试分配给变量的值存储在:new.stock_level中,触发器就是这种情况。 Here is a fix for the code you posted 这是您发布的代码的修复程序
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;
What value you need to extract? 你需要提取什么价值? To get values inserted in sales_table use 要在sales_table中插入值,请使用
:new.fieldname :new.fieldname
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.