简体   繁体   中英

Remove accents on a string field in mysql query

I have the following query:

SELECT * FROM main_creditperson WHERE name="Irene Olga López"

This will reutrn:

id         name
366354     Irene Olga López

Is there a simple way to do this in the query so the result is removed of all accents?

id         name
366354     Irene Olga Lopez

You can try to create a function to replace accents to a normal word.

Schema (MySQL v5.6)

CREATE TABLE main_creditperson(id int,name Nvarchar(50));

INSERT INTO main_creditperson VALUES (366354,N'Irene Olga López');


ALTER TABLE main_creditperson 
MODIFY name VARCHAR(50) CHARACTER SET utf8mb4      
      COLLATE utf8mb4_bin; 

DROP FUNCTION IF EXISTS fn_remove_accents;
DELIMITER |
CREATE FUNCTION fn_remove_accents( textvalue VARCHAR(10000) ) RETURNS VARCHAR(10000)

BEGIN

    SET @textvalue = textvalue;

    -- ACCENTS
    SET @withaccents = 'ŠšŽžÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜÝŸÞàáâãäåæçèéêëìíîïñòóôõöøùúûüýÿþƒ';
    SET @withoutaccents = 'SsZzAAAAAAACEEEEIIIINOOOOOOUUUUYYBaaaaaaaceeeeiiiinoooooouuuuyybf';
    SET @count = LENGTH(@withaccents);

    WHILE @count > 0 DO
        SET @textvalue = REPLACE(@textvalue, SUBSTRING(@withaccents, @count, 1), SUBSTRING(@withoutaccents, @count, 1));
        SET @count = @count - 1;
    END WHILE;

    SET @special = '!@#$%¨&*()_+=§¹²³£¢¬"`´{[^~}]<,>.:;?/°ºª+*|\\''';
    SET @count = LENGTH(@special);

    WHILE @count > 0 do
        SET @textvalue = REPLACE(@textvalue, SUBSTRING(@special, @count, 1), '');
        SET @count = @count - 1;
    END WHILE;

    RETURN @textvalue;

END
|
DELIMITER ;

Query #1

SELECT id,fn_remove_accents(name)  name
FROM main_creditperson 
WHERE name="Irene Olga López";

| id     | name             |
| ------ | ---------------- |
| 366354 | Irene Olga Lopez |

View on DB Fiddle


function Reference

If the COLLATION is any of the ..._ci variants, then accents are ignored when comparing. That is, no accent-stripping code is needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM