How to do a 'Proper case' formatting of a mysql column?
@Pascal's solution works on latin characters. Any meddling with different collations messes things up.
I think what @Pascal really meant goes more like this:
DELIMITER |
CREATE or replace FUNCTION func_proper( str VARCHAR(255) )
RETURNS VARCHAR(255)
BEGIN
DECLARE chr VARCHAR(1);
DECLARE lStr VARCHAR(255);
DECLARE oStr VARCHAR(255) DEFAULT '';
DECLARE i INT DEFAULT 1;
DECLARE bool INT DEFAULT 1;
DECLARE punct CHAR(17) DEFAULT ' ()[]{},.-_!@;:?/';
WHILE i <= LENGTH( str ) DO
BEGIN
SET chr = SUBSTRING( str, i, 1 );
IF LOCATE( chr, punct ) > 0 THEN
BEGIN
SET bool = 1;
SET oStr = concat(oStr, chr);
END;
ELSEIF bool=1 THEN
BEGIN
SET oStr = concat(oStr, UCASE(chr));
SET bool = 0;
END;
ELSE
BEGIN
SET oStr = concat(oStr, LCASE(chr));
END;
END IF;
SET i = i+1;
END;
END WHILE;
RETURN oStr;
END;
|
DELIMITER ;
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
In case there are only words in a single column ie. FirstName and LastName. We can concatenate the substrings.
select customer_name, concat(
upper(substring(substring_index(customer_name,' ',1),1,1)),
lower(substring(substring_index(customer_name,' ',1),2)) , ' ',
upper(substring(substring_index(customer_name,' ',-1),1,1)),
lower(substring(substring_index(customer_name,' ',-1),2))
) from customer;
You can combine CONCAT and SUBSTRING:
CONCAT(UCASE(SUBSTRING(`fieldName`, 1, 1)), LOWER(SUBSTRING(`fieldName`, 2)))