Case-insensitive REPLACE in MySQL?

后端 未结 8 2150
無奈伤痛
無奈伤痛 2020-12-05 10:00

MySQL runs pretty much all string comparisons under the default collation... except the REPLACE command. I have a case-insensitive collation and need to run a

8条回答
  •  醉梦人生
    2020-12-05 10:50

    This modification of Luist's answer allows one to replace the needle with a differently cased version of the needle (two lines change).

    DELIMITER |
    CREATE FUNCTION case_insensitive_replace ( REPLACE_WHERE text, REPLACE_THIS text, REPLACE_WITH text )
    RETURNS text
    DETERMINISTIC 
    BEGIN
      DECLARE last_occurency int DEFAULT '1';
    
      IF LENGTH(REPLACE_THIS) < 1 THEN
        RETURN REPLACE_WHERE;
      END IF;
    
      WHILE Locate( LCASE(REPLACE_THIS), LCASE(REPLACE_WHERE), last_occurency ) > 0  DO
        BEGIN
          SET last_occurency = Locate(LCASE(REPLACE_THIS), LCASE(REPLACE_WHERE), last_occurency);
          SET REPLACE_WHERE = Insert( REPLACE_WHERE, last_occurency, LENGTH(REPLACE_THIS), REPLACE_WITH);
           SET last_occurency = last_occurency + LENGTH(REPLACE_WITH);
        END;
      END WHILE;
      RETURN REPLACE_WHERE;
    END;
    |
    DELIMITER ;
    

提交回复
热议问题