Latest Entries »

Sunday, June 27, 2010

Changing Columns to Proper Case in MySQL - Using InitCap() function

MySQL String functions have lots of capabilities to manipulate the columns the way you wish to display. But apparently MySQL does not have any inbuilt function to convert the string to Proper Case. Some people understand this term as Sentence Case or Capitalized. However, on MySQL Dev site I found this amazing function which is worth quoting since it does exactly that.

DELIMITER $$
DROP FUNCTION IF EXISTS `initcap` $$
CREATE FUNCTION `initcap`(x char(30)) RETURNS char(30) CHARSET utf8
BEGIN
SET @str='';
SET @l_str='';
WHILE x REGEXP ' ' DO
    SELECT SUBSTRING_INDEX(x, ' ', 1) INTO @l_str;
    SELECT SUBSTRING(x, LOCATE(' ', x)+1) INTO x;
    SELECT CONCAT(@str, ' ', CONCAT(UPPER(SUBSTRING(@l_str,1,1)),LOWER(SUBSTRING(@l_str,2)))) INTO @str;
END WHILE;
RETURN LTRIM(CONCAT(@str, ' ', CONCAT(UPPER(SUBSTRING(x,1,1)),LOWER(SUBSTRING(x,2)))));
END $$
DELIMITER ;

Usage of this function would be as follows:-
- SELECT initcap('new delhi') returns "New Delhi"

Saving the article for my reference and for a lot of other people who might be looking for something similar.

3 comments:

glen said...

I would want it to uppercase also multi names, commonly used in Estonia, also skandinavia, like

girl name "Mari-liis" should be capitalized as "Mari-Liis"

Unknown said...

Glen

Try out

DELIMITER $$
DROP FUNCTION IF EXISTS `initcap` $$
CREATE FUNCTION `initcap`(x char(30)) RETURNS char(30) CHARSET utf8
BEGIN
SET @str='';
SET @l_str='';
WHILE x REGEXP '-' DO
SELECT SUBSTRING_INDEX(x, '-', 1) INTO @l_str;
SELECT SUBSTRING(x, LOCATE('-', x)+1) INTO x;
SELECT CONCAT(@str, ' ', CONCAT(UPPER(SUBSTRING(@l_str,1,1)),LOWER(SUBSTRING(@l_str,2)))) INTO @str;
END WHILE;
RETURN LTRIM(CONCAT(@str, '-', CONCAT(UPPER(SUBSTRING(x,1,1)),LOWER(SUBSTRING(x,2)))));
END $$
DELIMITER ;

This should solve your purpose. If you want both the spaces as well as hyphen functionality together, I am sure it is fairly simple to add it to this loop.

Regards
Tarun

kaincequebodeaux said...

MGM to begin legal sports betting on Maryland casino
The agreement with the Washington state sports betting 군산 출장샵 company MGM Resorts will allow the company to 군포 출장마사지 offer bettors 대구광역 출장마사지 both online 제천 출장마사지 and off-track betting on 여주 출장마사지