MySQL存储过程初学者错误

时间:2016-04-14 22:38:30

标签: mysql stored-procedures

我正在学习MySQL存储过程,但我对我尝试创建的过程感到有些困惑。

CREATE PROCEDURE tag_inserts
(
IN myTag VARCHAR(255), 
IN profileID INT(11)
)

BEGIN

INSERT IGNORE INTO tags(tag) VALUES(myTag);

SET @lid = LAST_INSERT_ID();

 IF(@lid = 0,
 (SELECT tagid FROM tags WHERE tag = myTag),
 (INSERT INTO profile_hashtags (pid,tagid) VALUES (profileID,@lid)));

END

当我执行它时,它会给我以下错误

  

您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以获得正确的语法,使用在  INTO profile_hashtags(pid,tagid)VALUES(profileID,@ lid)))附近;   END'在第13行

1 个答案:

答案 0 :(得分:2)

您使用的if()函数用于表达式的条件评估。你想要的是程序流控制IF compound statement syntax,它看起来像这样:

-- Some client apps require DELIMITER directives, and some don't.
DELIMITER //

CREATE PROCEDURE tag_inserts (IN myTag VARCHAR(255), IN profileID INT(11))
  BEGIN
    INSERT IGNORE INTO tags (tag)
      VALUES (myTag);
    SET @lid = LAST_INSERT_ID();
    IF @lid = 0 THEN
      SELECT tagid
        INTO @lid
        FROM tags
        WHERE tag = myTag;
      INSERT INTO profile_hashtags
          (pid, tagid)
        VALUES
          (profileID, @lid);
    END IF;
  END;

-- Some client apps require DELIMITER directives, and some don't.
//
DELIMITER ;

还要注意用于将选定值检索到过程变量中的SELECT ... INTO语法。