Proper case

from the Artful Common Queries page


The basic idea is...
  • lower-case the string
  • upper-case the first character if it is a-z, and any other a-z character that follows a punctuation character
Here is the function. To make it work with strings long than 128 characters, change its input and return declarations accordingly:
DROP FUNCTION IF EXISTS proper;
SET GLOBAL  log_bin_trust_function_creators=TRUE;
DELIMITER |
CREATE FUNCTION proper( str VARCHAR(128) )
RETURNS VARCHAR(128)
BEGIN
  DECLARE c CHAR(1);
  DECLARE s VARCHAR(128);
  DECLARE i INT DEFAULT 1;
  DECLARE bool INT DEFAULT 1;
  DECLARE punct CHAR(18) DEFAULT ' ()[]{},.-_\'!@;:?/'; -- David Rabby & Lenny Erickson added \'
  SET s = LCASE( str );
  WHILE i <= LENGTH( str ) DO -- Jesse Palmer corrected from < to <= for last char
    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 ;
select proper("d'arcy");
+------------------+
| proper("d'arcy") |
+------------------+
| D'Arcy           |
+------------------+
But there are always exceptions, for example some guy with that name will want it spelled d'Arcy.

Last updated 20 Jun 2024