BringMyCakeBack
BringMyCakeBack

Reputation: 1557

Checking Null in MySQL Nested If

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?

Upvotes: 0

Views: 136

Answers (3)

Rahul
Rahul

Reputation: 77876

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;

Upvotes: 1

Ravinder Reddy
Ravinder Reddy

Reputation: 24002

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

Upvotes: 1

Hackerman
Hackerman

Reputation: 12295

Try this:

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

Upvotes: 0

Related Questions