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.
My problem is extracting the information from the insert in order to obtain the correct value for the trigger variable @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. 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. 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;