mySQL用户定义函数中set命令的正确语法是什么?

时间:2011-04-05 13:35:55

标签: mysql function syntax user-defined-functions

尝试在mySQL 5.1中创建函数时收到以下错误:

Error Code : 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 '' at line 25 (0 ms taken)

这是我的代码:

DELIMITER $$  

CREATE
    FUNCTION removeMethodAndBackslash(input VARCHAR(40))
    RETURNS VARCHAR(20)
    BEGIN

    DECLARE loginName VARCHAR(40);
    SET loginName = input;

    IF SUBSTRING(loginName,7) LIKE '\b%' THEN
        SET loginName = 'b' + SUBSTRING(input,8);

    ELSE IF SUBSTRING(loginName,7) LIKE '\n%' THEN
        SET loginName = 'n' + SUBSTRING(input,8);

    ELSE IF SUBSTRING(loginName,7) LIKE '\t%' THEN
        SET loginName = 't' + SUBSTRING(input,8);

    ELSE IF SUBSTRING(loginName,7) LIKE '\r%' THEN
        SET loginName = 'r' + SUBSTRING(input,8);

    ELSE
        SET loginName = SUBSTRING(input,7);

    RETURN loginName;

END $$

DELIMITER ;

我已经玩了一段时间的语法,我确信它是一个我忽略的非常小的细节。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

您可以使用CASE...THEN...ELSE阻止

DELIMITER $$  

CREATE FUNCTION removeMethodAndBackslash(input VARCHAR(40))
RETURNS VARCHAR(20)
    BEGIN

    DECLARE loginName VARCHAR(40);

    SET loginName = 
       CASE WHEN SUBSTRING(input,7) LIKE '\b%' THEN 'b' + SUBSTRING(input,8)
            WHEN SUBSTRING(input,7) LIKE '\n%' THEN 'n' + SUBSTRING(input,8)
            WHEN SUBSTRING(input,7) LIKE '\t%' THEN 't' + SUBSTRING(input,8)
            WHEN SUBSTRING(input,7) LIKE '\r%' THEN 'r' + SUBSTRING(input,8)
            ELSE SUBSTRING(input,7)
       END;

    RETURN loginName;

END $$

答案 1 :(得分:1)

试试这个 -

DELIMITER $$  

CREATE
    FUNCTION removeMethodAndBackslash(input VARCHAR(40))
    RETURNS VARCHAR(20)
    BEGIN

    DECLARE loginName VARCHAR(40);
    SET loginName = input;

    IF SUBSTRING(loginName,7) LIKE '\b%' THEN
        SET loginName = 'b' + SUBSTRING(input,8);

    ELSEIF SUBSTRING(loginName,7) LIKE '\n%' THEN
        SET loginName = 'n' + SUBSTRING(input,8);

    ELSEIF SUBSTRING(loginName,7) LIKE '\t%' THEN
        SET loginName = 't' + SUBSTRING(input,8);

    ELSEIF SUBSTRING(loginName,7) LIKE '\r%' THEN
        SET loginName = 'r' + SUBSTRING(input,8);

    ELSE
        SET loginName = SUBSTRING(input,7);
    END IF;

    RETURN loginName;

END $$

DELIMITER ;