Using SQL Server, how do I split a string so I can access item x?
Take a string "Hello John Smith". How can I split the string by space and access the item at index 1 which should return "John"?
Using SQL Server, how do I split a string so I can access item x?
Take a string "Hello John Smith". How can I split the string by space and access the item at index 1 which should return "John"?
This question is not about a string split approach, but about how to get the nth element.
All answers here are doing some kind of string splitting using recursion,
CTE
s, multipleCHARINDEX
,REVERSE
andPATINDEX
, inventing functions, call for CLR methods, number tables,CROSS APPLY
s ... Most answers cover many lines of code.But - if you really want nothing more than an approach to get the nth element - this can be done as real one-liner, no UDF, not even a sub-select... And as an extra benefit: type safe
Get part 2 delimited by a space:
Of course you can use variables for delimiter and position (use
sql:column
to retrieve the position directly from a query's value):If your string might include forbidden characters (especially one among
&><
), you still can do it this way. Just useFOR XML PATH
on your string first to replace all forbidden characters with the fitting escape sequence implicitly.It's a very special case if - additionally - your delimiter is the semicolon. In this case I replace the delimiter first to '#DLMT#', and replace this to the XML tags finally:
UPDATE for SQL-Server 2016+
Regretfully the developers forgot to return the part's index with
STRING_SPLIT
. But, using SQL-Server 2016+, there isOPENJSON
.The documentation states clearly:
A string like
1,2,3
needs nothing more than brackets:[1,2,3]
.A string of words like
this is an example
needs to be["this","is","an"," example"]
.These are very easy string operations. Just try it out:
Here is a function that will accomplish the question's goal of splitting a string and accessing item X:
Usage:
Result:
Most of the solutions here use while loops or recursive CTEs. A set-based approach will be superior, I promise:
More on split functions, why (and proof that) while loops and recursive CTEs don't scale, and better alternatives, if splitting strings coming from the application layer:
On SQL Server 2016 or above, though, you should look at
STRING_SPLIT()
andSTRING_AGG()
:Yet another get n'th part of string by delimeter function:
and the usage:
which returns:
I use the answer of frederic but this did not work in SQL Server 2005
I modified it and I'm using
select
withunion all
and it worksAnd the result-set is: