sql - 表规范化(将逗号分隔的字段解析为单独的记录)

标签 sql sql-server tsql sql-server-2008 database-design

我有一个这样的表:

设备

DeviceId   Parts

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

我想创建一个表“Parts”,将数据从“Parts”列导出到新表。之后我将删除零件列

预期结果

零件

PartId PartName

  1      Part1
  2      Part2
  3      Part3
  4      Part4

设备部分

DeviceId PartId

  1      1
  1      2
  1      3
  2      2
  2      3
  2      4
  3      1

我可以在 SQL Server 2008 中不使用游标执行此操作吗?

最佳答案

-- 设置:

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')

--脚本:

declare @DevicePartTemp table(DeviceId int, PartName varchar(100))

insert @DevicePartTemp
select DeviceId, ltrim(x.value('.', 'varchar(100)'))
from
(
    select DeviceId, cast('<x>' + replace(Parts, ',', '</x><x>') + '</x>' 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

--结果:

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   

关于sql - 表规范化(将逗号分隔的字段解析为单独的记录),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6418214/

相关文章:

sql - 请解释一下所附的查询

sql-server - SQL Server - 更新全文目录索引的脚本

mysql - SQL,使用数学将行转换为列

sql - 根据最近的先前日期匹配两个表之间的值的最有效方法是什么?

mysql - 只显示 mysql 子查询返回 null 的行

mysql - LIKE 模式中的逻辑运算符

sql - 如果不为空,则对另一列进行唯一约束

SQL 过程在一行中返回结果

c# - 如何使用当前日期增加数字

sql - 遍历大量 "if exists update, else insert"语句?