Mysql extract first letter of each word in a specific column

后端 未结 5 1756
予麋鹿
予麋鹿 2021-01-16 02:36

I want to create an acronym column in a table. I want to be grab the first letter of each word from a \'name\' column, capitalize it, then concatenate all into an \'acronym\

5条回答
  •  半阙折子戏
    2021-01-16 03:07

    String manipulation of this kind is not what SQL is designed for, unless you want to write a stored procedure or UDF for it.

    SQL isn't really suited for string manipulation of this sort. You may do it somehow but why would you when better tools are available elsewhere? I went on a long search on Google to find such a query statement but I couldn't. Just use the following function to achieve what you want.

    drop function if exists initials;
    delimiter ||
    create function initials(str text) returns text
    begin
        declare result text default '';
        declare i int default 1;
    
        if(str is null) then
            return null;
        end if;
    
        set result = upper(substr(str, 1, 1));
    
        while(i <= length(str)) do
            if (substring(str, i, 1) = ' ')
            then
                set result = concat(result, upper(substr(str, i+1, 1)));
            end if;
           set i = i + 1;
        end while;
    
        return ucase(result);
    end;
    delimiter ;
    

提交回复
热议问题