在MySQL嵌套中检查Null如果

时间:2014-03-31 17:17:25

标签: mysql json if-statement

我正在尝试编写一个MySQL函数,该函数从格式化为JSON dict的文本字段中提取值。但是,出于某种原因,我无法使嵌套的IF语句在没有语法错误的情况下工作。

这是功能:

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 ;

以下是我遇到的错误:

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

对我失踪的事情有所了解吗?

3 个答案:

答案 0 :(得分:1)

删除条件周围的括号并检查;像

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

您也可以像

一样更改条件检查
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 :(得分:1)

key是保留字。

使用其他名称,例如jKey或使用反引号(`)将其接受

更改这些行

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

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

请参阅MySQL Reserved Words

答案 2 :(得分:0)

试试这个:

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