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

Community
  • 1
  • 1
Raphael Jeger
  • 5,024
  • 13
  • 48
  • 79

2 Answers2

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 ;
John Woo
  • 258,903
  • 69
  • 498
  • 492
  • that seems to work and you are the hero of my day... but could you explain what's the matter with "DELIMITER"? – Raphael Jeger Mar 21 '13 at 13:12
  • `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. – John Woo Mar 21 '13 at 13:14
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.

Mikhail Vladimirov
  • 13,572
  • 1
  • 38
  • 40