Declare variable MySQL trigger

后端 未结 2 850
一生所求
一生所求 2021-01-01 15:36

My question might be simple for you, if you\'re used to MySQL. I\'m used to PostgreSQL SGBD and I\'m trying to translate a PL/PgSQL script to MySQL.

Here is what I h

相关标签:
2条回答
  • 2021-01-01 16:00

    Agree with neubert about the DECLARE statements, this will fix syntax error. But I would suggest you to avoid using openning cursors, they may be slow.

    For your task: use INSERT...SELECT statement which will help you to copy data from one table to another using only one query.

    INSERT ... SELECT Syntax.

    0 讨论(0)
  • 2021-01-01 16:08

    All DECLAREs need to be at the top. ie.

    delimiter //
    
    CREATE TRIGGER pgl_new_user 
    AFTER INSERT ON users FOR EACH ROW
    BEGIN
        DECLARE m_user_team_id integer;
        DECLARE m_projects_id integer;
        DECLARE cur CURSOR FOR SELECT project_id FROM user_team_project_relationships WHERE user_team_id = m_user_team_id;
    
        SET @m_user_team_id := (SELECT id FROM user_teams WHERE name = "pgl_reporters");
    
        OPEN cur;
            ins_loop: LOOP
                FETCH cur INTO m_projects_id;
                IF done THEN
                    LEAVE ins_loop;
                END IF;
                INSERT INTO users_projects (user_id, project_id, created_at, updated_at, project_access) 
                VALUES (NEW.id, m_projects_id, now(), now(), 20);
            END LOOP;
        CLOSE cur;
    END//
    
    0 讨论(0)
提交回复
热议问题