yogesh yogesh - 3 months ago 12
MySQL Question

MySQL - Capital first letter of each word

Below is MySQL function to capitalize the first letter of every word in a string.

USE `db`$$

DROP FUNCTION IF EXISTS `UC_Words`$$

CREATE DEFINER=`root`@`localhost` FUNCTION `UC_Words`(str VARCHAR(255) ) RETURNS VARCHAR(255) CHARSET latin1
MODIFIES SQL DATA
DETERMINISTIC
BEGIN
DECLARE c CHAR(1);
DECLARE s VARCHAR(255);
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 ;


It's works fine for all Strings. But if I provide string "M R E" then its give "M R e" output.

plz suggest.

Answer

First execute below query

-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$

CREATE DEFINER=`root`@`localhost` FUNCTION `UC_FIRST`(oldWord VARCHAR(255)) RETURNS varchar(255) CHARSET latin1
RETURN CONCAT(UCASE(SUBSTRING(oldWord, 1, 1)),SUBSTRING(oldWord, 2))

Then execute below query

-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$

CREATE DEFINER=`root`@`localhost` FUNCTION `UC_Words`(oldName VARCHAR(255), delim VARCHAR(1), trimSpaces BOOL) RETURNS varchar(255) CHARSET latin1
BEGIN
    SET @oldString := oldName;
    SET @newString := "";

    tokenLoop: LOOP
    IF trimSpaces THEN SET @oldString := TRIM(BOTH " " FROM @oldString); END IF;

    SET @splitPoint := LOCATE(delim, @oldString);

    IF @splitPoint = 0 THEN
      SET @newString := CONCAT(@newString, UC_FIRST(@oldString));
      LEAVE tokenLoop;
    END IF;

    SET @newString := CONCAT(@newString, UC_FIRST(SUBSTRING(@oldString, 1, @splitPoint)));
    SET @oldString := SUBSTRING(@oldString, @splitPoint+1);
    END LOOP tokenLoop;

    RETURN @newString;
END

Then after call function

SELECT UC_Words("this is for testing"," ", TRUE);

Output below

This Is For Testing
Comments