0

I am trying to write a MySQL function that pulls a value out of a text field that is formatted as a JSON dict. However, for some reason I can't get the nested IF statement to work without syntax errors.

Here is the function:

DROP FUNCTION IF EXISTS json_key;
DELIMITER $$

CREATE FUNCTION `json_key`(`col` TEXT, `key` VARCHAR(255)) RETURNS VARCHAR(255)
DETERMINISTIC
BEGIN
    DECLARE ret VARCHAR(255);
    DECLARE pos INT;
    IF (col IS NULL) THEN SET ret = "";
    ELSEIF (col = "") THEN SET ret =  "";
    ELSEIF (LOCATE(key, col) = 0) THEN SET ret =  "";
    ELSE 
        SET pos := LOCATE(key, col);
        SET len := LENGTH(key);
        SET bg  := pos + len;
        SET ret = SUBSTR(col, bg, LOCATE('"', col, bg) - bg));
    END IF;
    RETURN ret;
END $$
DELIMITER ;

Here is the error I am getting:

ERROR 1064 (42000): 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 'key, col) = 0) THEN SET ret =  "";

ELSE 
SET pos := LOCATE(key, col);
SET len :=' at line 7

Any idea on what I'm missing?

3 Answers 3

1

key is a reserved word.

Either use a different name, say jKey or use backticks (`) to get it accepted

Change these lines:

ELSEIF (LOCATE(key, col) = 0) THEN SET ret =  "";
ELSE 
    SET pos := LOCATE(key, col);
    SET len := LENGTH(key);

To:

ELSEIF (LOCATE(`key`, col) = 0) THEN SET ret =  "";
ELSE 
    SET pos := LOCATE(`key`, col);
    SET len := LENGTH(`key`);

Refer to: MySQL Reserved Words

Sign up to request clarification or add additional context in comments.

Comments

1

Remove the parenthesis around the condition and check; like

ELSEIF LOCATE(key, col) = 0 THEN SET ret =  "";

You can as well change your condition checking like

IF (col IS NULL OR  col = "" OR LOCATE(key, col) = 0) THEN SET ret = "";
ELSE 
    SET pos := LOCATE(key, col);
    SET len := LENGTH(key);
    SET bg  := pos + len;
    SET ret = SUBSTR(col, bg, LOCATE('"', col, bg) - bg));
END IF;

1 Comment

Ravinder caught the error, but I voted up this one as well because it cleans up the overall structure.
0

Try this:

SET len := (coalesce(LENGTH(key),0));

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.