-- Sample data
declare @T table(ID int, CarData varchar(100))
insert into @T values
(1, 'Nissan:blue:20000,Ford:green:10000'),
(2, 'Nissan:steel:20001,Ford:blue:10001,Chevy:blue:10000,Ford:olive:10000')
-- Recursice CTE to get one row for each car
;with cte(ID, Car, CarData) as
(
select ID,
cast(substring(CarData+',', 1, charindex(',', CarData+',')-1) as varchar(100)),
stuff(CarData, 1, charindex(',', CarData), '')+','
from @T
where len(CarData) > 0
union all
select ID,
cast(substring(CarData, 1, charindex(',', CarData)-1) as varchar(100)),
stuff(CarData, 1, charindex(',', CarData), '')
from cte
where len(CarData) > 0
)
-- Use parsename to split the car data
select ID,
parsename(replace(Car, ':', '.'), 3) as Manufacture,
parsename(replace(Car, ':', '.'), 2) as Color,
parsename(replace(Car, ':', '.'), 1) as Cost
from cte
order by ID
Результат:
ID Manufacture Color Cost
-- ----------- ------ -----
1 Nissan blue 20000
1 Ford green 10000
2 Nissan steel 20001
2 Ford blue 10001
2 Chevy blue 10000
2 Ford olive 10000
Редактировать 1
У вас будут проблемы с parsename
, если цвет, стоимость или название производителя содержат .
. Если это так, попробуйте вместо этого.
-- Sample data
declare @T table(ID int, CarData varchar(100))
insert into @T values
(1, 'Nissan:blue:20000,Ford:green:10000'),
(2, 'Nissan:steel:20001,Ford:blue:10001,Chevy:blue:10000,Ford:olive:10000')
-- Recursice CTE to get one row for each car
;with cte(ID, Car, CarData) as
(
select ID,
cast(substring(CarData+',', 1, charindex(',', CarData+',')-1) as varchar(100)),
stuff(CarData, 1, charindex(',', CarData), '')+','
from @T
where len(CarData) > 0
union all
select ID,
cast(substring(CarData, 1, charindex(',', CarData)-1) as varchar(100)),
stuff(CarData, 1, charindex(',', CarData), '')
from cte
where len(CarData) > 0
)
-- Split the car data with substring
select ID,
substring(Car, 1, P1.Pos-1) as Manufacture,
substring(Car, P1.Pos+1, P2.Pos-P1.Pos-1) as Color,
substring(Car, P2.Pos+1, len(Car)-P2.Pos) as Cost
from cte
cross apply (select charindex(':', Car)) as P1(Pos)
cross apply (select charindex(':', Car, P1.Pos+1)) as P2(Pos)
order by ID