T-sql split string
In SQL Server 2016+, use STRING_SPLIT to split a string into rows:
This artery slicer chops your string into bite-sized rows. If you're stuck in the past with an older version, you'll need a combo of SUBSTRING and CHARINDEX or a custom function. Don't worry, we have covered that for you as well.
Pre-2016 options
The XML Parses it all
In SQL Server 2008 R2, the XML approach pulls through:
Your CSV just got an XML makeover. The CROSS APPLY method is the fashion police here, breaking the style-apart gaudy string into elegant rows.
Loopy Delimit-Inator
Or create a custom loop-master function to demarcate territory between delimit-able parts. Here’s an example:
Call this function into action with:
This function is basically a drooling baby, nibbling chunks of the input and spitting them into the output table.
Edge cases and optimization techniques
Space, the final frontier
Use spaces trimmers LTRIM and RTRIM to avoid choking on air:
Recursive CTEs and the Art of Recursion
Going with recursive CTEs? Let SQL Server know you're unlimited with OPTION (MAXRECURSION 0)
:
Speed Breakers
Set-based approaches are the F1 racers of SQL splitting. BYTE into gummy VARCHAR(MAX) data knowing that STRING_SPLIT
is faster than other custom or XML-based methods.
Play-doh delimiters
Replace Function
Got dirty delimiters? Clean them up with the REPLACE function before chucking them in the splitinator:
XML Method
XML method? No fret! Delimiter replacement is just an amendment in the REPLACE function:
Upgrade benefits and alternate solutions
Transition timeline
STRING_SPLIT
is the party you're missing if you haven't upgraded to at least SQL Server 2016.
Looking beyond SQL Server
Third-party tools or libraries can bring more tools to the table but check compliance and security.
Benchmark it!
Always benchmark your split methods, just like grandma used to do with her cookies. Performance insights can guide your choice of best approach.
Was this article helpful?