DELIMITER // CREATE TABLE t22 (s1 INTEGER)// CREATE TRIGGER t22_bi BEFORE INSERT ON t22 FOR EACH ROW BEGIN SET @x = 'Trigger was activated!'; SET NEW.s1 = 55; END;// INSERT INTO t22 VALUES (1)// SELECT @x, t22.* FROM t22// +------------------------+------+ | @x | s1 | +------------------------+------+ | Trigger was activated! | 55 | +------------------------+------+ 1 row in set (0.00 sec)
CREATE TABLE t25 (s1 INT, s2 CHAR(5), PRIMARY KEY (s1), CHECK (LEFT(s2,1)='A')) ENGINE=INNODB;
The CHECK means “insert and update are illegal unless the leftmost character of column s2 is 'A'”. MySQL doesn't support that. MySQL does support the CHECK clause for views, which is what I'd recommend. But just in case you insist on putting the equivalent of a CHECK clause on a base table, here's how you can do it with triggers.
CREATE TABLE t25 (s1 INT, s2 CHAR(5), PRIMARY KEY (s1)) ENGINE=INNODB// CREATE TRIGGER t25_bi BEFORE INSERT ON t25 FOR EACH ROW IF LEFT(NEW.s2,1)<>'A' THEN SET NEW.s1=0; END IF;// CREATE TRIGGER t25_bu BEFORE UPDATE ON t25 FOR EACH ROW IF LEFT(NEW.s2,1)<>'A' THEN SET NEW.s1=0; END IF;//
I only need BEFORE INSERT and BEFORE UPDATE triggers. DELETE triggers won't matter,
and AFTER triggers can't change NEW transition variables.
I have to prime the pump by inserting a row with s1=0. After that, any attempt to add or change
so that LEFT(s2,1) <> 'A' will fail. Try it with:
INSERT INTO t25 VALUES (0,'a') /* priming the pump */ // INSERT INTO t25 VALUES (5,'b') /* gets error '23000' */ //