I have a data like this, please help
id | name | value
----+---------+---------
1 | a, b | 12, 34
I want to get an output like this:
id | name | value
----+-------+---------
1 | a | 12
1 | b | 34
I have a data like this, please help
id | name | value
----+---------+---------
1 | a, b | 12, 34
I want to get an output like this:
id | name | value
----+-------+---------
1 | a | 12
1 | b | 34
Just another option (Gordon is way too fast for me)
The JSON [Key] is a proper sequence... assuming both columns have the same number of elements.
Example
Declare @YourTable Table ([id] varchar(50),[name] varchar(50),[value] varchar(50))
Insert Into @YourTable Values
(1,'a,b','12,34')
Select ID
,Name = max(case when Item='Name' then B.Value end)
,Value = max(case when Item='Value' then B.Value end)
From @YourTable A
Cross Apply (
Select [Key]
,Item = 'Name'
,Value
From OpenJSON( '["'+replace(replace([name],'"','\"'),',','","')+'"]' )
Union All
Select [Key]
,Item = 'Value'
,Value
From OpenJSON( '["'+replace(replace([value],'"','\"'),',','","')+'"]' )
) B
Group By ID,[Key]
Results
ID Name Value
1 a 12
1 b 34
One method is a recursive CTE:
with cte as (
select id, convert(varchar(max), null) as name, convert(varchar(max), null) as val,
convert(varchar(max), names + ',') as names, convert(varchar(max), vals + ',') as vals
from t
union all
select id,
convert(varchar(max), left(names, charindex(',', names) - 1)),
convert(varchar(max), left(vals, charindex(',', vals) - 1)),
convert(varchar(max), stuff(names, 1, charindex(',', names), '')),
convert(varchar(max), stuff(vals, 1, charindex(',', vals), ''))
from cte
where names like '%,%' and vals like '%,%'
)
select id, name, val
from cte
where name is not null;
Here is a db<>fiddle.