Xml数据节点值需要保存到Database表中

时间:2013-09-05 15:44:05

标签: xml sql-server-2008

这是我的XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Computer Name="WH7" Processior="Intel(R) Core(TM)2 Duo CPU P9600 @ 2.66GHz" 
          Manufacturer="Dell Inc." Model="Latitude E6500" Domain="WORKGROUP" 
          RAM="3536 MB" ServiceTag="DGQKTJ1">
    <BIOS Manufacturer="Dell Inc." Version="Phoenix ROM BIOS PLUS Version 1.10 A19"/>
</Computer>

我想将根节点(即<Computer>)属性值和子节点值(即BIOS)保存到下面的Asset表中。

Create Table Asset
(
   AssetId int Identity(100, 1),
   Name varchar(50),
   Processor varchar(50),
   Manufacturer varchar(100),
   Model varchar(100),
   Domain varchar(100),
   RAM  varchar(100),
   ServiceTag varchar(100),
   Version varchar(100)
)

任何人都可以帮助我。

1 个答案:

答案 0 :(得分:0)

您可以轻松地从<Computer>节点中提取信息并将其插入Asset
PS:注意:它是处理器 - 不是“processior”(两个i之后没有s

DECLARE @Input XML

SET @Input = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Computer Name="WH7" Processor="Intel(R) Core(TM)2 Duo CPU P9600 @ 2.66GHz" 
          Manufacturer="Dell Inc." Model="Latitude E6500" Domain="WORKGROUP" 
          RAM="3536 MB" ServiceTag="DGQKTJ1">
    <BIOS Manufacturer="Dell Inc." Version="Phoenix ROM BIOS PLUS Version 1.10 A19"/>
</Computer>'

INSERT INTO dbo.Asset(Name, Processor, Manufacturer, Model, Domain, RAM, ServiceTag)
    SELECT
        Name = @Input.value('(/Computer/@Name)[1]', 'varchar(50)'),
        Processor = @Input.value('(/Computer/@Processor)[1]', 'varchar(50)'),
        Manufacturer = @Input.value('(/Computer/@Manufacturer)[1]', 'varchar(50)'),
        Model = @Input.value('(/Computer/@Model)[1]', 'varchar(50)'),
        Domain = @Input.value('(/Computer/@Domain)[1]', 'varchar(50)'),
        RAM = @Input.value('(/Computer/@RAM)[1]', 'varchar(50)'),
        ServiceTag = @Input.value('(/Computer/@ServiceTag)[1]', 'varchar(50)')

但是完全不清楚的是你想如何将<BIOS>节点插入到这个表中,以及如何将这两行分开 - 或者它们是否以某种方式链接(这样你就知道哪个BIOS属于哪个)到哪台电脑......)