T-SQL Here is a T-SQL function that will handle this conversion. It will work for normal names and concatenations, like O'Brien and Moseley-Williams. It will not, however, work for joined names like VanWyck, or for compound names that are *meant* to be lower case, like Oscar de la Hoya.
CREATE FUNCTION dbo.pCase ( @strIn VARCHAR(255) ) RETURNS VARCHAR(255) AS BEGIN IF @strIn IS NULL RETURN NULL DECLARE @strOut VARCHAR(255), @i INT, @Up BIT, @c VARCHAR(2) SELECT @strOut = '', @i = 0, @Up = 1 WHILE @i <= DATALENGTH(@strIn) BEGIN SET @c = SUBSTRING(@strIn,@i,1) IF @c IN (' ','-','''') BEGIN SET @strOut = @strOut + @c SET @Up = 1 END ELSE BEGIN IF @up = 1 SET @c = UPPER(@c) ELSE SET @c = LOWER(@c) SET @strOut = @strOut + @c SET @Up = 0 END SET @i = @i + 1 END RETURN @strOut END GO |
Sample usage:
SELECT dbo.pCase('bill o''reilly'), dbo.pCase('bill van der wal'), dbo.pCase('mr. moseley-williams'), dbo.pCase('Joe VanWyck') |
For another T-SQL example, see
this function from Vyas.
VBScript Here is a VBScript version, based on the same logic. Since the logic is similar, the same disclaimers apply; there is no universal way, I believe, to handle proper casing correctly, 100% of the time.
<% Function pCase(strIn) strOut = "" boolUp = True For i = 1 To Len(strIn) c = Mid(strIn, i, 1) if c = " " or c = "'" or c = "-" then strOut = strOut & c boolUp = True Else If boolUp Then tc = Ucase(c) Else tc = LCase(c) End If strOut = strOut & tc boolUp = False End If Next pCase = strOut End Function %> |
Sample usage:
<% Response.Write pCase('bill o''reilly') & "<br>" Response.Write pCase('bill van der wal') & "<br>" Response.Write pCase('mr. moseley-williams') & "<br>" Response.Write pCase('Joe VanWyck') %> |
JScript / Regular Expressions Here is some code courtesy Chris Hohmann.
<script language=JScript runat=SERVER> function pCase(s) { return s.replace(/(\w)(\w*)/g,function ( strMatch, strFirst, strRest, intMatchPos, strSource ) { return strFirst.toUpperCase() +strRest.toLowerCase(); }); } </script> |
Sample usage:
<script language=JScript runat=SERVER> Response.Write(pCase('bill o\'reilly') + '<br>'); Response.Write(pCase('bill van der wal') + '<br>'); Response.Write(pCase('mr. moseley-williams') + '<br>'); Response.Write(pCase('Joe VanWyck') + '<br>'); </script> |
CSS Another option (which is even less flexible) is to use text-transform (only works for browsers with sufficient CSS support):
| <span style='text-transform:capitalize'>mr john moseley-williams</span> |
Be very cautious when deciding to employ any of these methods. Some cultures (and, more likely, individual people) are very sensitive to case sensitivity! You might consider just leaving their names the way they were entered.