I’m trying to create a trigger on my table, so that when I insert data, it tries to take the data from one column (Notes) and update another table’s (masterData) column notes (Additional) with the data. If it can’t find it, I want the insert statement to be copied to a different table (failedtofind). My trigger is below, but it reports that there is a syntax error on my IF statement, and I can’t quite get it working:
DELIMITER $$
TRIGGER `testdb`.`testTable`
AFTER INSERT ON `testdb`.`testTable`
FOR EACH ROW
BEGIN
IF ((SELECT PrimaryID FROM testdb.masterData WHERE PrimaryID = NEW.PrimaryID) > 0 )
UPDATE masterData AS t
SET t.Additional = NEW.Notes
WHERE t.PrimaryID = NEW.PrimaryID;
ELSE
INSERT IGNORE INTO failedtofind SET (all the columns);
END IF;
END$$
Also, is this the way I should be doing it? I’m a novice when it comes to databases, so, as always, if I’m doing something wrong, please feel free to correct me.
You are missing a
THENafter yourIF(...)it should beI am not sure what the
> 0is suppose to do – if no record with that PrimaryID is found the SELECT statement will evaluate toNULL(not 0). But it should still work as expected becauseNULL > 0evaluates toNULLand it will insert a row infailedtofind.