How to capitalize the first letter of each word in a string in SQL Server
Here's a quick solution using the STRING_AGG
and STRING_SPLIT
functions to capitalize each word in a string.
In essence, this code splits the string into words, capitalizes the first letter of each, and then stitches them back together.
Although this approach works perfectly for most scenarios, let's dive a little deeper to handle tougher edge cases, substantial data volumes, and SQL Server
's version constraints.
Tackling special requirements and considerations
Cap it all, consistently: Large dataset handling
In situations involving substantial volumes of data, it's paramount to devise a set-based solution for optimal performance. Here, we employ recursive Common Table Expressions (CTEs), eliminating the need for performance-degrading cursors and loops.
Bent the rules: Constraint handling
SQL Server
versions each come with unique quirks. For instance, STRING_SPLIT
is only available from SQL Server 2016 onwards. For earlier versions, leverage a different method like a user-defined function or a well-coordinated combo of CHARINDEX
and SUBSTRING
operations.
Special care for special characters
If your input string houses special characters, your solution should smartly capitalize only the first alphabet following a non-alphabet or space:
Implementing a reusable user-defined function
Reuse, Reduce, Recycle: Crafting a user-defined function
For the sake of reusability and isolation, compartmentalize the logic into a user-defined function (UDF):
Apply the UDF as follows:
Was this article helpful?