When working with textual data in SQL Server, formatting text to Title Case (also known as Proper Case) can be a common requirement. This is especially true in scenarios like creating cleanly formatted reports or standardizing input data. In this article, we’ll guide you through creating a User-Defined Function (UDF) to convert any text string into Title Case, covering everything from beginner-friendly explanations to advanced-level insights.
SQL Server provides extensive tools for text manipulation, but it doesn’t have a built-in function for converting strings to Title Case. By creating a User-Defined Function (UDF), we can easily format strings into Title Case, making them easier to read and more professional-looking.
This guide will walk you through building such a function, with detailed examples and real-world use cases to ensure you’re fully equipped to use it effectively.
Title Case refers to a string where the first letter of each word is capitalized, and all other letters are lowercase. For example:
hello world
"Hello World
"Title Case formatting is commonly used in:
john doe
" → "John Doe
")sql server basics
" → "SQL Server Basics
")UPPER()
and LOWER()
for case manipulation, but they don’t address word-level capitalization.Let’s create a scalar-valued UDF in SQL Server. Scalar-valued UDFs return a single value, which makes them perfect for this task.
STRING_SPLIT
(available in SQL Server 2016 and later) to process each word in the string.UPPER()
and SUBSTRING()
.Here’s a simple implementation:
CREATE FUNCTION dbo.fn_TitleCase (@InputString NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @Result NVARCHAR(MAX) = ''
DECLARE @Word NVARCHAR(100)
DECLARE @Position INT = 0
-- Add a space at the end to process the last word
SET @InputString = LTRIM(RTRIM(@InputString)) + ' '
WHILE CHARINDEX(' ', @InputString, @Position + 1) > 0
BEGIN
SET @Word = SUBSTRING(
@InputString,
@Position + 1,
CHARINDEX(' ', @InputString, @Position + 1) - @Position - 1
)
SET @Word = UPPER(LEFT(@Word, 1)) + LOWER(SUBSTRING(@Word, 2, LEN(@Word) - 1))
SET @Result = @Result + @Word + ' '
SET @Position = CHARINDEX(' ', @InputString, @Position + 1)
END
RETURN RTRIM(@Result)
END
GO
SELECT dbo.fn_TitleCase('hello world') AS TitleCaseOutput
Hello World
SELECT dbo.fn_TitleCase('SQL server is AWESOME') AS TitleCaseOutput
Sql Server Is Awesome
If you have a table of customer names stored in inconsistent formats:
UPDATE Customers
SET Name = dbo.fn_TitleCase(Name)
WHERE IsActive = 1
For product listings:
SELECT ProductID, dbo.fn_TitleCase(Description) AS FormattedDescription
FROM Products
WHERE Category = 'Electronics'
Converting text strings to Title Case in SQL Server is a common task that can be easily handled with a custom UDF. This tutorial covered everything from creating the function to understanding its practical applications. With this knowledge, you can confidently clean and format text data in your SQL Server databases.
Comments