The below MySQL function will show how to capitalize first letter of each word in a string.

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 ;

Test 1

SELECT initcap('This is test string')

Output

This Is Test String

Test 2

SELECT initcap('UNITED states Of AmERIca')

Output

United States Of America

Thanks for reading.

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

Your email address will not be published. Required fields are marked *