为什么我的这个简单功能不会保存?

时间:2013-06-06 13:15:32

标签: mysql sql

我在MySql中组合了一个函数。没什么大不了的。但它不会存钱。我在HeidiSql中使用它。

CREATE DEFINER=`root`@`localhost` FUNCTION `mainLinks`(`nid` INT)
    RETURNS varchar(1500)
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
BEGIN
    DECLARE aid INT;
    DECLARE atype INT;
    DECLARE aparent INT;
    DECLARE ausername VARCHAR(32);
    DECLARE auserid INT;
    DECLARE aCOUNTRY VARCHAR(2);
    DECLARE aOutput VARCHAR(1500); 

    SELECT id, type, parent, userName, userId, country
    INTO aid, atype, aparent, auserName, auserId, acountry
    FROM arraytest
    WHERE id = nid;

    CASE atype
    WHEN 1 THEN SET aOutput = 'One';
    WHEN 2 THEN SET aOutput = 'Two';
    WHEN 3 THEN SET aOutput = 'Three';
    ELSE 'Neither';
    END;

  RETURN (aOutput);
END

导致所有问题的是case,我已经尝试了一切。移动和删除;。但没有什么能使它发挥作用。

这是错误:

`/* SQL Error (1064): 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 ''Neither';
    END;

  RETURN (aOutput);
END' at line 26 */`

此功能中没有第26行。你能帮忙吗?

包含数据和其他内容的表格 Fiddle

2 个答案:

答案 0 :(得分:2)

你的CASE条款都错了

应该是

SET aOutput = CASE atype
              WHEN 1 THEN 'One'
              WHEN 2 THEN 'Two'
              WHEN 3 THEN 'Three'
              ELSE 'Neither'
END;

修改

CREATE DEFINER=`root`@`localhost` FUNCTION `mainLinks`(`nid` INT)
    RETURNS varchar(1500)
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
BEGIN
    DECLARE aid INT;
    DECLARE atype INT;
    DECLARE aparent INT;
    DECLARE ausername VARCHAR(32);
    DECLARE auserid INT;
    DECLARE aCOUNTRY VARCHAR(2);
    DECLARE aOutput VARCHAR(1500); 

    SELECT id, type, parent, userName, userId, country
    INTO aid, atype, aparent, auserName, auserId, acountry
    FROM arraytest
    WHERE id = nid;

    SET aOutput = CASE atype
        WHEN 1 THEN CONCAT (auserName, ' other stuff')
        WHEN 2 THEN auserName
        WHEN 3 THEN 'other stuff'
        ELSE 'default stuff'
    END;
    RETURN (aOutput);
END

某些非常类似的测试在sqlfiddle

上正常

答案 1 :(得分:0)

这是导致错误的案例陈述

CASE atype
WHEN 1 THEN SET aOutput = 'One';
WHEN 2 THEN SET aOutput = 'Two';
WHEN 3 THEN SET aOutput = 'Three';
ELSE 'Neither';
END;

应该是

CASE atype
    WHEN 1 THEN SET aOutput = 'One'
    WHEN 2 THEN SET aOutput = 'Two'
    WHEN 3 THEN SET aOutput = 'Three'
    ELSE 'Neither'
END CASE;