Search code examples
mysqlsqlcursordatabase-trigger

Trigger Error 1326 MySQL


I'm having a problem creating a trigger in MySQL. My "tb_pessoa" table stores my users' data. I would like that when a new insert is made, it stores in the "tb_email" table the user's email, checking if it already exists, but when performing the query with the cursor, it says that the cursor was not opened, and it was. What can it be?

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

Solution

  • You don't need to use a cursor, just execute an INSERT that gets the values from a 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
    

    Also, if NEW.nm_email doesn't contain any wildcard characters % or _ you should use = instead of LIKE.