2

This

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

fails with

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 '' at line 4

Why?

This function is related to the problem here:

mysql insert if not exists on joined tables

1
  • Have you set delimiter to something different from ;? Commented Mar 21, 2013 at 13:09

2 Answers 2

3

Try to change the DELIMITER and remove the parenthesis around the INSERT statement.

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 ;
Sign up to request clarification or add additional context in comments.

2 Comments

that seems to work and you are the hero of my day... but could you explain what's the matter with "DELIMITER"?
DELIMITER changes the termination symbol on the query and allowing you to execute multiple statements that contains ;. Remember that every after ; closes the statement that is why when changing to another symbol allows you to execute multiple statement without breaking it.
2

Type to set delimiter to ;; like this:

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 ;

Delimiter is used by MySQL client (not sever) to split input into separate queries. Default delimiter is ; so MySQL client sent the following query to the server:

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

BEGIN
DECLARE tagID BIGINT

Which is incomplete and thus incorrect.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.