小编典典

声明变量MySQL触发器

sql

如果您习惯使用MySQL,我的问题对您来说可能很简单。我已经习惯了PostgreSQL SGBD,并且试图将PL / PgSQL脚本转换为MySQL。

这是我所拥有的:

delimiter //

CREATE TRIGGER pgl_new_user 
AFTER INSERT ON users FOR EACH ROW
BEGIN
    DECLARE m_user_team_id integer;
    SELECT id INTO m_user_team_id FROM user_teams WHERE name = "pgl_reporters";

    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;

    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//

但是MySQL Workbench给我一个错误DECLARE m_projects_id。我不太明白,因为我在上面两行有相同的说明…

有什么提示吗?

编辑:Neubert解决了此错误。谢谢。

但是,当我尝试插入用户时:

Error Code: 1329. No data - zero rows fetched, selected, or processed

你有什么主意吗 ?还是更好,您知道我如何获得更好的错误消息吗?


阅读 235

收藏
2021-03-17

共1个答案

小编典典

所有DECLARE都必须位于顶部。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//
2021-03-17