How can I achieve initcap functionality in MySQL?

Solution 1:

Sometime back I was looking for a built-in initcap/ucfirst function in MySQL but unfortunately couldn't find such string functions so decided to write my own.. thanks to the MySQL community member who corrected the bug in my function & posted it back.

DELIMITER $$

DROP FUNCTION IF EXISTS `test`.`initcap`$$

CREATE FUNCTION `initcap`(x char(30)) RETURNS char(30) CHARSET utf8
READS SQL DATA
DETERMINISTIC
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: 

select initcap('This is test string');

Solution 2:

DELIMITER $$

CREATE
   FUNCTION `test`.`initcap`(input VARCHAR(255))
   RETURNS VARCHAR(255) 
BEGIN
DECLARE len INT;
DECLARE i INT;

SET len   = CHAR_LENGTH(input);
SET input = LOWER(input);
SET i = 0;

WHILE (i < len) DO
    IF (MID(input,i,1) = ' ' OR i = 0) THEN
        IF (i < len) THEN
            SET input = CONCAT(
                LEFT(input,i),
                UPPER(MID(input,i + 1,1)),
                RIGHT(input,len - i - 1)
            );
        END IF;
    END IF;
    SET i = i + 1;
END WHILE;

RETURN input;
END$$

DELIMITER ;

usage: initcap("hello world") output: Hello World

usage: initcap("HELLO WORLD") output: Hello World

This converts first letter of each word in the string to capital.

Solution 3:

DELIMITER $$

DROP FUNCTION IF EXISTS `test`.`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 ;

Solution 4:

CREATE FUNCTION `upperfirst`(x varchar(255)) RETURNS varchar(255) CHARSET latin1

RETURN concat( upper(substring(x,1,1)),lower(substring(x,2)) );