How to do a 'Proper case' formatting of a mysql column?

前端 未结 5 1293
无人共我
无人共我 2020-12-09 15:32

Is it possible in mysql to format a column in Proper Case?

Example: Proper(\"ABSALOM\") = \"Absalom\"

I have searched a lot and I think MySQL d

5条回答
  •  难免孤独
    2020-12-09 16:15

    You would think that the world’s most popular open source database, as MySQL like to call itself, would have a function for making items title case (where the first letter of every word is capitalized). Sadly it doesn’t.

    This is the best solution i found Just create a stored procedure / function that will do the trick

    mysql> 
    DROP FUNCTION IF EXISTS proper;
    SET GLOBAL  log_bin_trust_function_creators=TRUE;
    DELIMITER |
    CREATE FUNCTION proper( str VARCHAR(128) )
    RETURNS VARCHAR(128)
    BEGIN
    DECLARE c CHAR(1);
    DECLARE s VARCHAR(128);
    DECLARE i INT DEFAULT 1;
    DECLARE bool INT DEFAULT 1;
    DECLARE punct CHAR(17) DEFAULT ' ()[]{},.-_!@;:?/';
    SET s = LCASE( str );
    WHILE i <= LENGTH( str ) DO   
        BEGIN
    SET c = SUBSTRING( s, i, 1 );
    IF LOCATE( c, punct ) > 0 THEN
    SET bool = 1;
    ELSEIF bool=1 THEN
    BEGIN
    IF c >= 'a' AND c <= 'z' THEN
    BEGIN
    SET s = CONCAT(LEFT(s,i-1),UCASE(c),SUBSTRING(s,i+1));
    SET bool = 0;
    END;
    ELSEIF c >= '0' AND c <= '9' THEN
    SET bool = 0;
    END IF;
    END;
    END IF;
    SET i = i+1;
    END;
    END WHILE;
    RETURN s;
    END;
    |
    DELIMITER ;
    

    then

    update table set col = proper(col)
    

    or

    select proper( col ) as properCOl 
    from table 
    

    Tada Your are welcome

提交回复
热议问题