Table Normalization (Parse comma separated fields into individual records)

前端 未结 4 687
北荒
北荒 2021-01-13 03:31

I have a table like this:

Device

DeviceId   Parts

1          Part1, Part2, Part3
2          Part2, Part3, Part4
3          Part1
         


        
4条回答
  •  执念已碎
    2021-01-13 04:03

    -- Setup:

    declare @Device table(DeviceId int primary key, Parts varchar(1000))
    declare @Part table(PartId int identity(1,1) primary key, PartName varchar(100))
    declare @DevicePart table(DeviceId int, PartId int)
    
    insert @Device
    values
        (1, 'Part1, Part2, Part3'),
        (2, 'Part2, Part3, Part4'),
        (3, 'Part1')
    

    --Script:

    declare @DevicePartTemp table(DeviceId int, PartName varchar(100))
    
    insert @DevicePartTemp
    select DeviceId, ltrim(x.value('.', 'varchar(100)'))
    from
    (
        select DeviceId, cast('' + replace(Parts, ',', '') + '' as xml) XmlColumn
        from @Device
    )tt
    cross apply
        XmlColumn.nodes('x') as Nodes(x)
    
    
    insert @Part
    select distinct PartName
    from @DevicePartTemp
    
    insert @DevicePart
    select tmp.DeviceId, prt.PartId
    from @DevicePartTemp tmp 
        join @Part prt on
            prt.PartName = tmp.PartName
    

    -- Result:

    select *
    from @Part
    
    PartId      PartName
    ----------- ---------
    1           Part1
    2           Part2
    3           Part3
    4           Part4
    
    
    select *
    from @DevicePart
    
    DeviceId    PartId
    ----------- -----------
    1           1
    1           2
    1           3
    2           2
    2           3
    2           4
    3           1   
    

提交回复
热议问题