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"?
If your database has compatibility level of 130 or higher then you can use the STRING_SPLIT function along with OFFSET FETCH clauses to get the specific item by index.
To get the item at index N (zero based), you can use the following code
To check the compatibility level of your database, execute this code:
SIMPLE SOLUTION FOR PARSING FIRST AND LAST NAME
In my case (and in many others it seems...), I have a list of first and last names separated by a single space. This can be used directly inside a select statement to parse first and last name.
Here is a UDF which will do it. It will return a table of the delimited values, haven't tried all scenarios on it but your example works fine.
You would call it like this:
Edit: Updated solution to handle delimters with a len>1 as in :
Try this:
Test it like this:
I know it's an old Question, but i think some one can benefit from my solution.
SQL FIDDLE
Advantages:
Limitations:
Note: the solution can give sub-string up to to N.
To overcame the limitation we can use the following ref.
But again the above solution can't be use in a table (Actaully i wasn't able to use it).
Again i hope this solution can help some-one.
Update: In case of Records > 50000 it is not advisable to use
LOOPS
as it will degrade the PerformanceYou may find the solution in SQL User Defined Function to Parse a Delimited String helpful (from The Code Project).
You can use this simple logic: