Submitted byCategory
Review Cycle
.
Public
Joachim Mutter/sysarc
on 03/27/2009 at 10:22 AM
SQL\Code

SPLIT

Sometimes I run into a situation, where I need the ability to separate stings into single peaces and additionally I need that result as a table. The T-SQL Code for separating a string is no secret and to build this result in a return table is also quite easy.

The needed UDF function, called Split(), which do that for us gets a string to separate and the separator as input parameters and returns a table with the parts and positions as rows like the following figure shows :




So for example, I had a recursive function, which gets the organistion of a company from a Parent-Child oriented table. The result was a string like "John Doe/John Miller/Doris Day" which should be interpretated as the hierarchy "CEO/Teamleader/Worker".

For some customer evaluations we need the result of that function as flat entries like the following :
If we had a function described above, this would be quite simple, because we can separate the parts be a number and flattens the hierarchy string with this trick, like the following SQL Statement shows.


And here is a simple code to test that stuff: