Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What’s the best way to capitalise the first letter of each word in a string in SQL Server

What’s the best way to capitalise the first letter of each word in a string in SQL Server.

like image 439
Magpie Avatar asked Sep 10 '08 19:09

Magpie


People also ask

How do you capitalize the first character of each word in a string?

At first, you need to split() the string on the basis of space and extract the first character using charAt(). Use toUpperCase() for the extracted character.

How do you capitalize a word in SQL?

If you want to display a string in uppercase, use the SQL UPPER() function. This function takes only one argument: the string column that you want to convert to uppercase.

How do you capitalize every word in a string?

Use title() to capitalize the first letter of each word in a string in python. Python Str class provides a member function title() which makes each word title cased in string. It means, it converts the first character of each word to upper case and all remaining characters of word to lower case.

How do you auto capitalize the first letter of every word?

To use a keyboard shortcut to change between lowercase, UPPERCASE, and Capitalize Each Word, select the text and press SHIFT + F3 until the case you want is applied.


1 Answers

From http://www.sql-server-helper.com/functions/initcap.aspx

CREATE FUNCTION [dbo].[InitCap] ( @InputString varchar(4000) )  RETURNS VARCHAR(4000) AS BEGIN  DECLARE @Index          INT DECLARE @Char           CHAR(1) DECLARE @PrevChar       CHAR(1) DECLARE @OutputString   VARCHAR(255)  SET @OutputString = LOWER(@InputString) SET @Index = 1  WHILE @Index <= LEN(@InputString) BEGIN     SET @Char     = SUBSTRING(@InputString, @Index, 1)     SET @PrevChar = CASE WHEN @Index = 1 THEN ' '                          ELSE SUBSTRING(@InputString, @Index - 1, 1)                     END      IF @PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(')     BEGIN         IF @PrevChar != '''' OR UPPER(@Char) != 'S'             SET @OutputString = STUFF(@OutputString, @Index, 1, UPPER(@Char))     END      SET @Index = @Index + 1 END  RETURN @OutputString  END GO 

There is a simpler/smaller one here (but doesn't work if any row doesn't have spaces, "Invalid length parameter passed to the RIGHT function."):

http://www.devx.com/tips/Tip/17608

like image 87
Espo Avatar answered Oct 05 '22 18:10

Espo