SQL Capitalize First Letter - SQL Capitalize String
This SQL tutorial shares T-SQL scripts to capitalize string for SQL Server developers.
Sample SQL codes capitalize first letter of words in a sentence or in a string.
Our input is a SQL string that the first letters of each word is converted to upper case letters by SQL codes given in this tutorial.
We know that words in a sentence are distinguished by SPACE character.
Capitalize String in SQL using WHILE Loop
Following SQL code block starts with declaration of input string variable.
The first SELECT command where string functions STUFF() and LOWER() is used, lowers all characters in the given SQL string and replaces the first letter of the string with its upper letter.
We all know that all sentences start with upper case characters. So we implement this requirement in this SQL code line.
The second code block is SQL WHILE loop where I check for space characters and replace the first character following the spece with its upper case version.
Just before WHILE loop and at the end of the inner SQL code block of WHILE loop, I search for the space characters using CHARINDEX function
SQL capitalize first letters or convert to upper letter after space characters in a string
If this SQL code is enough for you, let's wrap this SQL script into a user-defined function and create your UDF function to capitalize string
This UDF user-defined function for capitalize could be used as follows:
Capitalize First Letters in a String using SQL Split and Concatenate
An other SQL solution for capitalization is to split the variable sentence into words then capitalize first letter. Finally concatenate string using SQL.
In below sample SQL code, I use following SQL SPLIT function first using space character as seperator
That is the output of our second method for capitalizing string variables using SQL split methods and then replacing the first character of each splitted string fragment with its upper case value.
Of course, SQL Server database developers can also convert above SQL code block into a user-defined function for converting first letters into capital letters. Here it is:
I hope these two Capitalize SQL functions help database developers building solutions on SQL Server