I am using version 5.0 of mysql.
I'm trying to create a trigger to check if one entry(name of Food) exists in the other table.
I´ve done this:
delimiter //
CREATE TRIGGER verifyExists BEFORE INSERT ON Sold
FOR EACH ROW
BEGIN
IF NEW.nameF not in (
select A.nameF
From Available D
where (NEW.nameF = A.nameF and NEW.nameR = A.nameR)
)
END IF;
END;
//
delimiter ;
this doesen't work, why?
To create a trigger, we need to change the delimiter. Inserting the row into Table1 activates the trigger and inserts the records into Table2. To insert record in Table1. To check if the records are inserted in both tables or not.
Moreover, triggers are ideal for validation because they can be executed before data is inserted or updated. Triggers can also can also prevent a database transaction from being applied while providing an error message.
The trigger event that initiates the trigger action can be an INSERT, DELETE, UPDATE, or a SELECT statement. The MERGE statement can also be the triggering event for an UPDATE, DELETE, or INSERT trigger.
You can create multiple triggers for the same subject table, event, and activation time. The order in which those triggers are activated is the order in which the triggers were created.
You have a couple of errors:
delimiter //
CREATE TRIGGER verifyExists BEFORE INSERT ON Sold
FOR EACH ROW
BEGIN
IF NEW.nameF not in (
select A.nameF
From Available A -- CHANGED THE ALIAS TO A
where (NEW.nameF = A.nameF and NEW.nameR = A.nameR)
) THEN -- MISSING THEN
CALL `Insert not allowed`;
END IF;
END;
//
delimiter ;
sqlfiddle demo
If you could use SIGNAL, it is the best way, but since it was only introduced in mysql 5.5, you will have to do it by other route. One way is to call a non existant function, like showed above. From this answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With