MySQL Trigger - Storing a SELECT in a variable

后端 未结 6 1308
孤独总比滥情好
孤独总比滥情好 2020-12-02 22:16

I have a trigger in which I want to have a variable that holds an INT I get from a SELECT, so I can use it in two IF statements instead of calling the SEL

6条回答
  •  隐瞒了意图╮
    2020-12-02 22:31

    You can declare local variables in MySQL triggers, with the DECLARE syntax.

    Here's an example:

    DROP TABLE IF EXISTS foo;
    CREATE TABLE FOO (
      i SERIAL PRIMARY KEY
    );
    
    DELIMITER //
    DROP TRIGGER IF EXISTS bar //
    
    CREATE TRIGGER bar AFTER INSERT ON foo
    FOR EACH ROW BEGIN
      DECLARE x INT;
      SET x = NEW.i;
      SET @a = x; -- set user variable outside trigger
    END//
    
    DELIMITER ;
    
    SET @a = 0;
    
    SELECT @a; -- returns 0
    
    INSERT INTO foo () VALUES ();
    
    SELECT @a; -- returns 1, the value it got during the trigger
    

    When you assign a value to a variable, you must ensure that the query returns only a single value, not a set of rows or a set of columns. For instance, if your query returns a single value in practice, it's okay but as soon as it returns more than one row, you get "ERROR 1242: Subquery returns more than 1 row".

    You can use LIMIT or MAX() to make sure that the local variable is set to a single value.

    CREATE TRIGGER bar AFTER INSERT ON foo
    FOR EACH ROW BEGIN
      DECLARE x INT;
      SET x = (SELECT age FROM users WHERE name = 'Bill'); 
      -- ERROR 1242 if more than one row with 'Bill'
    END//
    
    CREATE TRIGGER bar AFTER INSERT ON foo
    FOR EACH ROW BEGIN
      DECLARE x INT;
      SET x = (SELECT MAX(age) FROM users WHERE name = 'Bill');
      -- OK even when more than one row with 'Bill'
    END//
    

提交回复
热议问题