I have a situation in which I don’t want inserts to take place (the transaction should rollback) if a certain condition is met. I could write this logic in the application code, but say for some reason, it has to be written in MySQL itself (say clients written in different languages will be inserting into this MySQL InnoDB table) [that’s a separate discussion].
Table definition:
CREATE TABLE table1(x int NOT NULL);
The trigger looks something like this:
CREATE TRIGGER t1 BEFORE INSERT ON table1
FOR EACH ROW
IF (condition) THEN
NEW.x = NULL;
END IF;
END;
I am guessing it could also be written as(untested):
CREATE TRIGGER t1 BEFORE INSERT ON table1
FOR EACH ROW
IF (condition) THEN
ROLLBACK;
END IF;
END;
But, this doesn’t work:
CREATE TRIGGER t1 BEFORE INSERT ON table1 ROLLBACK;
You are guaranteed that:
- Your DB will always be MySQL
- Table type will always be InnoDB
- That NOT NULL column will always stay the way it is
Question: Do you see anything objectionable in the 1st method?
From the trigger documentation:
Your second option couldn’t be created. However:
So Eric’s suggestion to use a query that is guaranteed to result in an error is the next option. However, MySQL doesn’t have the ability to raise custom errors — you’ll have false positives to deal with. Encapsulating inside a stored procedure won’t be any better, due to the lack of custom error handling…
If we knew more detail about what your condition is, it’s possible it could be dealt with via a constraint.
Update
I’ve confirmed that though MySQL has CHECK constraint syntax, it’s not enforced by any engine. If you lock down access to a table, you could handle limitation logic in a stored procedure. The following trigger won’t work, because it is referencing the table being inserted to:
..results in MySQL error 1235.