Im having some trouble with using the if else construct in sql triggers in MySQL. The tables below are just used for testing.
First Table:
CREATE TABLE `test2`.`t1` (
`c1` VARCHAR(5) NOT NULL,
`c2` VARCHAR(45) NULL,
`c3` VARCHAR(45) NULL,
PRIMARY KEY (`c1`));
My second table:
CREATE TABLE `test2`.`t2` (
`cc1` VARCHAR(5) NOT NULL,
`cc2` VARCHAR(45) NULL,
`cc3` VARCHAR(45) NULL,
PRIMARY KEY (`cc1`));
and the third:
CREATE TABLE `test`.`t3` (
`ccc1` VARCHAR(5) NOT NULL,
`ccc2` VARCHAR(45) NULL,
`ccc3` VARCHAR(45) NULL,
PRIMARY KEY (`cc1`));
c1 is the primary key for both cc1 and ccc1.
The trigger I am using is:
DROP TRIGGER IF EXISTS `test`.`t1_AFTER_UPDATE`;
DELIMITER $$
USE `test`$$
CREATE DEFINER=`root`@`localhost` TRIGGER `t1_AFTER_UPDATE` AFTER UPDATE ON
`t1` FOR EACH ROW
BEGIN
DECLARE start varchar(1);
set start=substring((c2),1,1);
IF(start='S') THEN
UPDATE t2
SET cc2 = NEW.c2
WHERE cc1 = NEW.c1;
else
UPDATE t3
SET ccc2 = NEW.c2
WHERE ccc1 = NEW.c1;
END IF;
END$$
DELIMITER ;
Basically, if the user updates t1.c2, then t2.cc2 OR t3.ccc2 must be updated. If t1.c2 of the NEW.c2 starts with the letter S, then t2.cc2 must be updated, else t3.ccc2 must be updated.
The query executes without a hitch but wont let me update the value of c2:
Executing:
UPDATE `test2`.`t1` SET `c2` = '24' WHERE (`c1` = 'M123');
Operation failed: There was an error while applying the SQL script to the database.
ERROR 1054: 1054: Unknown column 'c1' in 'field list'
SQL Statement: