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"?
Pure set-based solution using
TVF
with recursiveCTE
. You canJOIN
andAPPLY
this function to any dataset.Usage:
Result:
In my opinion you guys are making it way too complicated. Just create a CLR UDF and be done with it.
Well, mine isn't all that simpler, but here is the code I use to split a comma-delimited input variable into individual values, and put it into a table variable. I'm sure you could modify this slightly to split based on a space and then to do a basic SELECT query against that table variable to get your results.
The concept is pretty much the same. One other alternative is to leverage the .NET compatibility within SQL Server 2005 itself. You can essentially write yourself a simple method in .NET that would split the string and then expose that as a stored procedure/function.
This pattern works fine and you can generalize
note FIELD, INDEX and TYPE.
Let some table with identifiers like
Then, you can write
splitting and casting all parts.