T-sql split string based on delimiter
In T-SQL, you can split a string with the STRING_SPLIT
function. You feed it two parameters - the string and the delimiter:
This returns rows for 'sample', 'text', 'to', 'split'. It works like a dream from SQL Server 2016 upwards.
For the folks using older versions, don't worry - I've got you covered below. So, whether you're stuck in the Stone Age or cruising in the future, there's something for everyone here.
Pre-2016 SQL Server: Splitting strings the hard way
Before SQL Server 2016, there wasn't a built-in function to split strings, but that doesn't mean it was impossible. Oh, no - just a bit more elaborate.
Using CHARINDEX and SUBSTRING
If the built-in STRING_SPLIT
is not available, you can still split strings in older versions of SQL Server using other built-in functions:
Multiple delimiters? Meet recursive CTEs
If you're dealing with multiple delimiters, you can use a recursive CTE to spill the beans:
Using LEFT and RIGHT to slice'n'dice
If you know the position of the delimiter, why not use LEFT and RIGHT functions to slice your strings?
The flexibility of UNION ALL
Breaking down long strings into manageable pieces is a breeze with UNION ALL:
Protecting against nulls and empty strings
Always handle potential null or empty values by providing default values where necessary with ISNULL or COALESCE functionalities:
Was this article helpful?