MySQL创建函数失败

时间:2013-03-21 13:08:23

标签: mysql sql function

CREATE FUNCTION getTagID(tag VARCHAR(100)) RETURNS BIGINT

BEGIN
DECLARE tagID BIGINT;
            SET tagID = (SELECT id FROM tags WHERE text = tag);
IF tagID IS NULL
THEN
            (INSERT INTO tags (text) VALUES (tag));
            SET tagID = (SELECT LAST_INSERT_ID());
END IF;
RETURN tagID;
END

失败
  

您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在第4行的''附近使用正确的语法

为什么?

此功能与此处的问题有关:

mysql insert if not exists on joined tables

2 个答案:

答案 0 :(得分:3)

尝试更改DELIMITER并删除INSERT语句周围的括号。

DELIMITER $$
CREATE FUNCTION getTagID(tag VARCHAR(100)) 
RETURNS BIGINT
BEGIN
    DECLARE tagID BIGINT;
    SET tagID = (SELECT id FROM tags WHERE text = tag);
    IF tagID IS NULL THEN
        INSERT INTO tags (text) VALUES (tag); -- don't put inside parenthesis
        SET tagID = (SELECT LAST_INSERT_ID());
    END IF;
    RETURN tagID;
END $$
DELIMITER ;

答案 1 :(得分:2)

键入以将分隔符设置为;;,如下所示:

DELIMITER ;;

CREATE FUNCTION getTagID(tag VARCHAR(100)) RETURNS BIGINT
BEGIN
  DECLARE tagID BIGINT;
  SET tagID = (SELECT id FROM tags WHERE text = tag);
  IF tagID IS NULL
  THEN
    INSERT INTO tags (text) VALUES (tag);
    SET tagID = (SELECT LAST_INSERT_ID());
  END IF;
  RETURN tagID;
END;;

DELIMITER ;

MySQL客户端(而不是服务器)使用分隔符将输入拆分为单独的查询。默认分隔符为;,因此MySQL客户端将以下查询发送到服务器:

CREATE FUNCTION getTagID(tag VARCHAR(100)) RETURNS BIGINT

BEGIN
DECLARE tagID BIGINT

哪个不完整,因此不正确。