Table Normalization (Parse comma separated fields into individual records)

前端 未结 4 684
北荒
北荒 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:14

    You will need a Tally table to accomplish this without a cursor.

    Follow the instructions to create a tally table here: Tally Tables by Jeff Moden

    This script will put the table into your Temp database, so you probably want to change the "Use DB" statement

    Then you can run the script below to insert a breakdown of Devices and Parts into a temp table. You should then be able to join on your part table by the part name (to get the ID) and insert into your new DevicePart table.

    select *, 
    --substring(d.parts, 1, t.n)
    substring(d.parts, t.n, charindex(', ', d.parts + ', ',t.n) - t.n) 'Part'
    into #devicesparts
    from device d
    cross join tally t
    where t.n < (select max(len(parts))+ 1 from device)
    and substring(', ' + d.parts, t.n, 1) = ', '
    

提交回复
热议问题