我的MySql查询中的错误在哪里创建触发器

时间:2017-04-11 11:29:00

标签: mysql random triggers phpmyadmin passwords

我有一个stu表,其中包含许多列(name,lname,username,pass和else),我希望在每个新用户注册之后或之前插入一个长度为8或6个字符的数字和字母的随机唯一字符串第一次登录时每个新用户的密码。 经过多次搜索后发现此代码:

    declare ready int default 0;
    declare rnd_str text;

    while not ready do
        set rnd_str := lpad(conv(floor(rand()*pow(36,6)), 10, 36), 6, 0);
        if not exists (select * from stu where pass = rnd_str) then
            set new.pass = rnd_str;
            set ready := 1;
        end if;
    end while;

我尝试通过phpmyadmin创建触发器,点击GO按钮后给我一个错误。

谁能帮我解决这个问题?

phpmyadmin中的

错误是这样的文字:

“处理您的请求时发生了一个或多个错误:

The following query has failed: "CREATE TRIGGER `set_random_8char_pass` BEFORE INSERT ON `stu` FOR EACH ROW declare ready int default 0; declare rnd_str text; while not ready DO set rnd_str := lpad(conv(floor(rand()*pow(36,6)), 10, 36), 6, 0); if not exists (select * from stu where pass = rnd_str) then set new.pass = rnd_str; set ready := 1; end if; end while;"

MySQL said: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'declare ready int default 0; declare rnd_str text; while not ready' at line 1

感谢所有

1 个答案:

答案 0 :(得分:1)

  

仅允许在BEGIN ... END复合语句中使用DECLARE   并且必须在任何其他陈述之前开始。

阅读https://dev.mysql.com/doc/refman/5.7/en/declare.html

所以你的触发器代码应该是这样的。

CREATE TRIGGER `set_random_8char_pass` BEFORE INSERT ON `stu` FOR EACH ROW 

BEGIN
  declare ready int default 0;
  declare rnd_str text;

  while not ready DO set rnd_str := lpad(conv(floor(rand()*pow(36,6)),        10, 36), 6, 0);
     if not exists (select * from stu where pass = rnd_str)
     then
       set new.pass = rnd_str;
       set ready := 1;
     end if;
   end while;
END