我在MySQL中创建触发器时遇到问题。我的" tb_pessoa"表存储我的用户'数据。我希望在制作新插件时,它会存储在" tb_email"列出用户的电子邮件,检查它是否已经存在,但是当用光标执行查询时,它表示光标没有打开,它就是。它能是什么?
CREATE DEFINER=`root`@`localhost` TRIGGER `db_agenda`.`tb_pessoa_AFTER_INSERT` AFTER INSERT ON `tb_pessoa` FOR EACH ROW
BEGIN
declare id_email, id_tipo_email int(11);
declare nm_email varchar(100);
declare cr_email cursor for
select id_email, nm_email, id_tipo_email
from tb_email
where nm_email like new.nm_email;
declare continue handler for sqlstate '02000'
open cr_email;
lp_email: loop
fetch cr_email into id_email, nm_email, id_tipo_email;
if (id_email = null) then
insert into tb_email set
id_email = (select max(id_email)+1 from tb_email),
nm_email = nm_email,
id_tipo_email = 1;
close cr_email;
leave lp_email;
end if;
end loop lp_email;
close cr_email;
END
答案 0 :(得分:1)
您不需要使用游标,只需执行一个INSERT
来获取SELECT
的值。
CREATE TRIGGER tb_pessoa_AFTER_INSERT AFTER INSERT ON tb_pessoa
ON EACH ROW
INSERT INTO tb_email (nm_email, id_tipo_email, id_email)
SELECT e.nm_email, 1, @id_email := @id_email + 1
FROM tb_email AS e
CROSS JOIN (SELECT @id_email := MAX(id_email) FROM tb_email) AS i
WHERE e.nm_email LIKE NEW.nm_email
此外,如果NEW.nm_email
不包含任何通配符%
或_
,则应使用=
代替LIKE
。