简体   繁体   中英

SQL InitCap that Uppercase some special words

How can i modify this InitCap function so that it always will uppercase AB when its in the end of the string and has a space before it.

  • test Ab <-- should display AB
  • testab <-- should display ab
  • abtest <-- should displat ab

    DELIMITER $$

     DROP FUNCTION IF EXISTS `CapitializeFirstCharInEveryWord`$$ CREATE FUNCTION `CapitializeFirstCharInEveryWord`(x char(100)) RETURNS char(100) 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$$ 

You want to capitalize last word in string? You can do it in simple way. Description in comments.

CREATE FUNCTION `CapitalizeLastWord`(x char(100)) RETURNS char(100) CHARSET utf8
BEGIN
-- detect has x space
SET @space_pos_reverse = LOCATE(' ', REVERSE(x)); 

-- if not return unchanged x
IF @space_pos_reverse = 0 THEN RETURN x; 
END IF;

-- getting last space position
SET @last_space_pos = LENGTH(x)-@space_pos_reverse+1; 

-- split x to 2 parts, 2nd part gettin UPPER
RETURN CONCAT(SUBSTRING(x, 1, @last_space_pos), UPPER(SUBSTRING(x, @last_space_pos+1)) ); 

END$$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM