Case-insensitive REPLACE in MySQL?

后端 未结 8 2096
無奈伤痛
無奈伤痛 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:49

    In case of 'special' characters there is unexpected behaviour:

    SELECT case_insensitive_replace('A', 'Ã', 'a')
    

    Gives

    a
    

    Which is unexpected... since we only want to replace the à not A

    What is even more weird:

    SELECT LOCATE('Ã', 'A');
    

    gives

    0
    

    Which is the correct result... seems to have to do with encoding of the parameters of the stored procedure...

    0 讨论(0)
  • 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 ;
    
    0 讨论(0)
提交回复
热议问题