This cannot be done without a stored procedure or function, unfortunately. However, I figured out how to maintain the function in my application. Borrowing the basic idea of โโthe procedure from this answer , I came up with the following:
DELIMITER | CREATE FUNCTION checkit(doit INTEGER, message VARCHAR(256)) RETURNS INTEGER DETERMINISTIC BEGIN IF doit IS NULL OR doit = 0 THEN SIGNAL SQLSTATE 'ERR0R' SET MESSAGE_TEXT = message; END IF; RETURN doit; END; |
The idea is that this function can be used in triggers as a CHECK or inline constraint in SQL statements. Returning to my original need for an error if the user does not exist, I now use the checkit() function as follows:
SELECT checkit(COUNT(*), 'User "foo" does not exist') FROM mysql.user WHERE user = 'foo';
If user foo exists, this query returns an integer. If the user does not exist, he throws an error with the message defined there.
Would you like to use the function for a control limit? He is an example (imitation of this answer ), with the tip of the hat to @ rouland-bouman:
CREATE TRIGGER mytabletriggerexample BEFORE INSERT FOR EACH ROW BEGIN SET @dummy := checkit( NEW.important_value) >= (fancy * dancy * calculation), 'Your meaningful error message goes here' ); END;
I would rather use DO rather than setting a dummy variable, but a MySQL error prevents this from working, alas.
theory
source share