从字符串中删除连续的重复字符

时间:2019-01-08 13:00:10

标签: mysql function duplicates

我正在尝试构建一个函数,该函数将从字符串中删除重复的字符。只有彼此跟随的字符。例如: “ AAABBBCCCDDAABB”必须为“ ABCDAB”。我做了下面的代码,但是没有用。你能帮忙吗?我是Mysql开发的新手...

  id prevId
1 cd     ab
2 ef     cd

1 个答案:

答案 0 :(得分:0)

CREATE FUNCTION `REMOVE_DUPLICATE_CHAR_FROM_STRING` (`aString` VARCHAR(50) )
RETURNS VARCHAR(50) CHARSET utf8
BEGIN
    DECLARE result VARCHAR(50) DEFAULT '';
    DECLARE prev CHAR(1) DEFAULT '';
    DECLARE c CHAR(1) DEFAULT '';
    DECLARE i TINYINT DEFAULT 1;
    DECLARE len TINYINT;

    SET len = LENGTH(aString);
    WHILE(i <= len) DO
        SET c = SUBSTRING(aString, i, 1);
        IF c != prev THEN
            SET result = CONCAT(result, c);
            SET prev = c;
        END IF;
        SET i = i + 1;
    END WHILE;
    RETURN result;
END