如果您习惯使用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
你知道吗?或者更好,你知道我怎么能得到更好的错误信息吗?
答案 0 :(得分:25)
所有DECLARE都需要位于顶部。即
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//
答案 1 :(得分:1)
同意关于DECLARE语句的neubert,这将修复语法错误。但我建议你避免使用开放游标,它们可能会很慢。
对于您的任务:使用INSERT ... SELECT语句,它将帮助您仅使用一个查询将数据从一个表复制到另一个表。