Is there a simple way to convert MySQL data into Title Case?

后端 未结 11 2226
太阳男子
太阳男子 2020-11-27 15:35

I have a MySQL table where all the data in one column was entered in UPPERCASE, but I need to convert in to Title Case, with recognition of \"small words\" akin to the Darin

11条回答
  •  情书的邮戳
    2020-11-27 15:48

    My solution for simple proper case:

    CREATE FUNCTION `proper_case`(str varchar(128)) RETURNS varchar(128)
    BEGIN
    DECLARE n, pos INT DEFAULT 1;
    DECLARE sub, proper VARCHAR(128) DEFAULT '';
    
    if length(trim(str)) > 0 then
        WHILE pos > 0 DO
            set pos = locate(' ',trim(str),n);
            if pos = 0 then
                set sub = lower(trim(substr(trim(str),n)));
            else
                set sub = lower(trim(substr(trim(str),n,pos-n)));
            end if;
    
            set proper = concat_ws(' ', proper, concat(upper(left(sub,1)),substr(sub,2)));
            set n = pos + 1;
        END WHILE;
    end if;
    
    RETURN trim(proper);
    END
    

    Use it as:

    SELECT proper_case("JOHN DOE");
    

    Output:

    John Doe
    

提交回复
热议问题