Parsing / breaking character separated values in a table in one query

,

There might be number of ways to accomplish this task but getting the result with a single query is sort of a challenge. I will explain to accomplish this task with an example.Consider a table having following data,

 

Declare @vTable Table(id int,val varchar(100))
Insert into @vTable Values (1,'Atif Sheikh2 Sheikh123')
Insert into @vTable Values (2,'Asif Sheikh1 Sheikh2 Sheikh3')

 

Now if you want to break the space separated values in the above table as;

ID Val

1 Atif

1 Sheikh2

1 Sheikh123

2 Asif

2 Sheikh1

2 Sheikh2

2 Sheikh3

 

the query is stated in the code.

 

Let me explain the above mentioned query. As you can see that i have used a recursive function CTE.The first query in the CTE query is

;Select id,substring(val,0,case when charindex(' ',val,0) = 0 then Len(val) else charindex(' ',val,0) + 1 end) as val,charindex(' ',val,0) + 1 strpos 
from @vTable

This creates the master record for parsing the string. This loads the first value in the required data set and to use in the second part. Here I used strpos column to get the position to parse the next value in the character separated string. It is just the length of the previous parsed value.

The second part is;

Select b.id,substring(b.val,strpos,case when charindex(' ',b.val,strpos) = 0 then Len(b.val) else charindex(' ',b.val,strpos) - strpos end) as val,charindex(' ',b.val,strpos) + 1 strpos 
from @vTable b
Inner Join wcte on wcte.id = b.ID
and wcte.strpos <> 1

 

This query uses the posintion in strpos column and parses the next value. And as it is recursive, it goes on until the strpos > 1. strpos, as you can see in the first part of the query, is the charindex of the character which is used to separate the values in the string.

That is it...

Declare @vTable Table(id int,val varchar(100))

Insert into @vTable Values (1,'Atif Sheikh2 Sheikh123')
Insert into @vTable Values (2,'Asif Sheikh1 Sheikh2 Sheikh3') 
 

;with wcte (id,val,strpos) as

(
Select id,substring(val,0,case when charindex(' ',val,0) = 0 then Len(val) else charindex(' ',val,0) + 1 end) as val
,charindex(' ',val,0) + 1 strpos from @vTable
Union all
Select b.id,substring(b.val,strpos,case when charindex(' ',b.val,strpos) = 0 then Len(b.val) else charindex(' ',b.val,strpos) - strpos end) as val
,charindex(' ',b.val,strpos) + 1 strpos 
from @vTable b
Inner Join wcte on wcte.id = b.ID
and wcte.strpos <> 1
)Select id,Val from wcte order by id

Rate

3.57 (7)

Share

Share

Rate

3.57 (7)