Another post for me that is simple and hopefully serves as an example for people trying to get blogging as #SQLNewBloggers.
I saw a post on using STRING_SPLIT() with cross apply recently, and as I was reading, I realized that I hadn’t adopted this very often in code. Mostly it’s not something I need to deal with, but recently my wife did give me some data and asked to reformat it, and I used STRING_SPLIT(). I thought it was a nice easy problem, so I decided to write about it.
The dataset that she gave me was formatted something like this:
What she wanted was a report that provided data more like this:
This was more complex in the past, and hard in T-SQL as string manipulation isn’t great. However, STRING_SPLIT makes this easier. Not great, but easier.
While STRING_SPLIT is a function, it is a table-valued function, meaning that it is used as the source for a data set. Rather than being in the SELECT column list, we would use this in the FROM clause as another table. Or anyplace a table can be used.
The basics of this would be:
FROM dbo.ClassSchedule AS cs
CROSS APPLY STRING_SPLIT(students, ',') AS ss
Using this code, I would get a list of students.
The STRING_SPLIT returns this single column, value, which is the string passed in split by the separator. I could see this more simply with this code:
FROM STRING_SPLIT('alpha,beta,delta,gamma',',') AS ss
This returns these items:
A few more examples:
The important thing to note here is that this is a simple substring based on the separator, with no other processing. Spaces or any other character outside the separator is left in the result.
There also is no ordering of the results. While this appears to be in the same order in these simple examples, this is not guaranteed, meaning the ordering of the substrings might not match the original order.
This is a good way to easily split up data that you have stuffed into a large character field, but it has limitations, so use it carefully.
This post took me about 15 minutes to write after spending 5 minutes setting up some test data. I was using string_split to clean up some data and decided to make a few notes, then built a new table with some strings in it to help me explain how it works.
A good example of a post you could write, perhaps noting when this was released or comparing this to a way of splitting these strings with a more complex T-SQL query.