Reputation: 5364
I'm looking for a t-sql function to get a string like:
a:b,c:d,e:f
and convert it to a table like
ID Value
a b
c d
e f
Anything I found in Internet incorporated single column parsing (e.g. XMLSplit function variations) but none of them letting me describe my string with two delimiters, one for column separation & the other for row separation.
Can you please guiding me regarding the issue? I have a very limited t-sql knowledge and cannot fork those read-made functions to get two column solution?
Upvotes: 0
Views: 1634
Reputation: 6622
You can use a custom SQL Split function in order to separate data-value columns Here is a sql split function that you can use on a development system It returns an ID value that can be helpful to keep id and value together
You need to split twice, first using "," then a second split using ";" character
declare @str nvarchar(100) = 'a:b,c:d,e:f'
select
id = max(id),
value = max(value)
from (
select
rowid,
id = case when id = 1 then val else null end,
value = case when id = 2 then val else null end
from (
select
s.id rowid, t.id, t.val
from (
select * from dbo.Split(@str, ',')
) s
cross apply dbo.Split(s.val, ':') t
) k
) m group by rowid
Upvotes: 1
Reputation: 1271161
You can find a split()
function on the web. Then, you can do string logic:
select left(val, charindex(':', val)) as col1,
substring(val, charindex(':', val) + 1, len(val)) as col2
from dbo.split(@str, ';') s(val);
Upvotes: 1