No need for creating a function if it is a one timer. The below works just fine:
-- Capitalize first letter of each word in r.name field
SELECT TRIM(CONCAT(
CONCAT(UPPER(SUBSTRING(cname1,1,1)),SUBSTRING(cname1,2)) , " ",
CONCAT(UPPER(SUBSTRING(cname2,1,1)),SUBSTRING(cname2,2)) , " ",
CONCAT(UPPER(SUBSTRING(cname3,1,1)),SUBSTRING(cname3,2))))
FROM (
SELECT
@num_spaces := 1 + LENGTH(c_name) - LENGTH(REPLACE(c_name, ' ', '')) AS
num_spaces,
SUBSTRING_INDEX(CONVERT(c_name,CHAR), ' ', 1) AS cname1,
IF(@num_spaces > 1, SUBSTRING_INDEX(SUBSTRING_INDEX(c_name, ' ', 2), ' ', -1), '') AS cname2,
IF(@num_spaces > 2, SUBSTRING_INDEX(SUBSTRING_INDEX(c_name, ' ', 3), ' ', -1), '') AS cname3
FROM (SELECT (CASE
WHEN UPPER(r.name)COLLATE latin1_general_cs =r.name THEN LOWER(TRIM(r.name))
ELSE TRIM(r.name)
END) AS c_name,r.name
FROM table r) cr) ncr;
NOTE: The IF clause should be equal to or more than the value of @num_spaces. The current sql will take care of at max 3 words. You may add more if required.