2017-11-10 126 views
0

我在創建觸發器時遇到了問題。我的「tb_pessoa」表存儲我的用戶數據。我希望在創建一個新插入時,它會在「tb_email」表中存儲用戶的電子郵件,檢查它是否已經存在,但是當用光標執行查詢時,表示光標未打開,而且是。它會是什麼?觸發錯誤1326 MySQL

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

'id_email'是一個自動增量列嗎? – Barmar

+0

不,它是通過max(id_email)+ 1的子查詢插入的 –

+0

爲什麼不將它更改爲auto_increment?然後它會自動完成。 – Barmar

回答

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

+0

好主意,我沒有想到,謝謝(y) –

+0

我唯一需要做的就是用max_()+ 1的子查詢id_email –

+0

如果你這樣做您將在所有添加的行中使用相同的'id_email'。我已經更新了答案,以顯示如何爲插入的每一行增加它。 – Barmar