将XML属性保存到SQL Server中的Table

时间:2015-10-15 06:13:04

标签: sql sql-server xml attributes

您好我有XML数据,其属性作为SQL的输入,我需要将其插入到我的表中。 XML数据

<?xml version="1.0" encoding="ISO-8859-1"?>
<MESSAGEACK>

<GUID GUID="kfafb30" SUBMITDATE="2015-10-15 11:30:29" ID="1">
<ERROR SEQ="1" CODE="28681" />
</GUID>

<GUID GUID="kfafb3" SUBMITDATE="2015-10-15 11:30:29" ID="1">
<ERROR SEQ="2" CODE="286381" />
</GUID>

</MESSAGEACK>

我希望将其插入格式

下面
GUID         SUBMIT DATE          ID          ERROR SEQ     CODE
kfafb3   2015-10-15 11:30:29      1          1             28681
kfafb3   2015-10-15 11:30:29      1          1             2868

请帮忙。

2 个答案:

答案 0 :(得分:4)

查看MSDN中的XPathxml Data Type Methods。这是一种可能的方式:

declare @xml As XML = '...you XML string here...'
INSERT INTO YourTable
SELECT 
    guid.value('@GUID', 'varchar(100)') as 'GUID'
    ,guid.value('@SUBMITDATE', 'datetime') as 'SUBMIT DATE'
    ,guid.value('@ID', 'int') as 'ID'
    ,guid.value('ERROR[1]/@SEQ', 'int') as 'SEQ'
    ,guid.value('ERROR[1]/@CODE', 'int') as 'CODE'
FROM @xml.nodes('/MESSAGEACK/GUID') as x(guid)

结果:

enter image description here

答案 1 :(得分:2)

将其粘贴到一个空的查询窗口并执行。适应您的需求:

DECLARE @xml XML=
'<?xml version="1.0" encoding="ISO-8859-1"?>
<MESSAGEACK>

<GUID GUID="kfafb30" SUBMITDATE="2015-10-15 11:30:29" ID="1">
<ERROR SEQ="1" CODE="28681" />
</GUID>

<GUID GUID="kfafb3" SUBMITDATE="2015-10-15 11:30:29" ID="1">
<ERROR SEQ="2" CODE="286381" />
</GUID>

</MESSAGEACK>';

SELECT Msg.Node.value('@GUID','varchar(max)') AS [GUID] --The value is no GUID, if the original values are, you could use uniqueidentifier instead of varchar(max)
      ,Msg.Node.value('@SUBMITDATE','datetime') AS SUBMITDATE
      ,Msg.Node.value('@ID','int') AS ID
      ,Msg.Node.value('(ERROR/@SEQ)[1]','int') AS [ERROR SEQ]
      ,Msg.Node.value('(ERROR/@CODE)[1]','int') AS CODE
FROM @xml.nodes('/MESSAGEACK/GUID') AS Msg(Node)