« Off to MySQL 2005 | Main | Day in San Francisco »

April 16, 2005

ucasefirst Function in MySQL

I've been playing with stored functions in MySQL 5.0.x since the first alpha was released. If you're using 5.0.x and have always wanted a function that will return a string with the first character in caps and the rest in lower case, here it is:

create function ucasefirst (phrase varchar(255)) returns varchar(255)
return concat(ucase(substr(phrase,1,1)),substr(lcase(phrase),2));
The restult when calling:
mysql> select ucasefirst("tHIS will TEST the fUnction.");
+--------------------------------------------+
| ucasefirst("tHIS will TEST the fUnction.") |
+--------------------------------------------+
| This will test the function. |
+--------------------------------------------+
1 row in set (0.00 sec)
This function is common in most scripting languages I've used, although might be named something else; ucfirst, upperfirst, firsttoupper, firstuc etc. So why not in MySQL? Simple to do with stored functions.

The cool thing about stored functions in MySQL 5 is you can build functions right in the MySQL client, that operate just like the built in functions. It's no longer necessary to write code in C like you did with pre-5.0 UDFs.

Posted by mike at April 16, 2005 12:32 AM