Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It cannot be done without a stored procedure or function, unfortunately. I figured out how to support a function in my app, though. Borrowing the basic procedure idea from <a href="https://stackoverflow.com/a/16644480/79202">this answer</a>, I've come up with this:</p> <pre><code>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; | </code></pre> <p>The idea is that the function can be used in triggers like a <code>CHECK</code> constraint, or inline in SQL statements. Getting back to my original need to throw an error if a user does not exist, I now use the <code>checkit()</code> function like this:</p> <pre><code>SELECT checkit(COUNT(*), 'User "foo" does not exist') FROM mysql.user WHERE user = 'foo'; </code></pre> <p>If user <code>foo</code> exists, this query returns an integer. If the user does not exist, it throws an error with the message defined there.</p> <p>Want to use the function for a check constraint, too? He's an example (mimicking <a href="https://stackoverflow.com/a/9737269/79202">this answer</a>), with a tip of the hat to @rouland-bouman:</p> <pre><code>CREATE TRIGGER mytabletriggerexample BEFORE INSERT FOR EACH ROW BEGIN SET @dummy := checkit( NEW.important_value) &gt;= (fancy * dancy * calculation), 'Your meaningful error message goes here' ); END; </code></pre> <p>I would rather use <code>DO</code>, rather than setting a dummy variable, but <a href="http://bugs.mysql.com/bug.php?id=69647" rel="nofollow noreferrer">a MySQL bug</a> prevents that from working, alas.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload