7

Possible Duplicate:
MySQL - Capitalize first letter of each word, in existing table

Is there a MySQL String function equivalent to PHP ucwords() function.

The end goal is to use MySQL to uppercase the first letter of each word in a string.

Example.

-- The name field in the table holds "JOHN DOE"
SELECT LOWER(name)
  FROM table

This will give me the result 'john doe'

I want the result to be 'John Doe'

Community
  • 1
  • 1
Jim
  • 522
  • 1
  • 3
  • 7

1 Answers1

14

This article shows you how to define a Proper Case in MySQL: Proper Case.

Included in case of link rot:

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           | 
+------------------+ 
Levi Morrison
  • 19,116
  • 7
  • 65
  • 85
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • 3
    nice resource, lazy answer, the function is called `Proper Case` to help future people find it http://www.artfulsoftware.com/infotree/queries.php#122 – Moak Jan 04 '11 at 02:44
  • This will screw up on possessive nouns, such as "John's", resulting in "John'S". This can be fixed by adding a `c_peek` variable for the next character, and checking it right after `IF c >= 'a' AND c <= 'z' THEN` for a space. e.g. `IF NOT (c = 's' && c_peek = ' ') THEN` – Craige May 05 '14 at 18:57