我是使用XML的新手。我已经回顾了几个帖子,并且很难绕过这个任务。
我有一个名为tbl.AccountLogs的SQL Server 2008R2表,其中包含列 - 源,日期,ID和详细信息(xml数据)
我试图通过XML字段“Details”解析成几列。该字段可以包含许多标记和嵌套标记。
以下是一个例子:
<errors>
<error date = '1394746874'>
<detail id = '3342867234'>
<arg type = '0'><![CDATA[512,107,741,184]]></arg>
<arg type = '0'><![CDATA[274,877,906,944]]></arg>
<arg type = '0'><![CDATA[J:\]]></arg>
<arg type = '0'><![CDATA[TestLine.img]]></arg>
</detail>
</error>
<error date = '1394747022'>
<detail id = '3342867234'>
<arg type = '0'><![CDATA[28,594,585,600]]></arg>
<arg type = '0'><![CDATA[21,474,836,480]]></arg>
<arg type = '0'><![CDATA[C:\Safe\]]></arg>
<arg type = '0'><![CDATA[{BigMonster}]]></arg>
</detail>
</error>
</errors>
如前所述,“错误”的数量可以改变每条记录,但“arg类型”和“详细ID”是一致的。
示例输出将是:
非常感谢任何帮助!
答案 0 :(得分:1)
试试这个,希望它可以帮助你朝着正确的方向前进:
--if temp table exists drop it
IF OBJECT_ID('tempdb..#tmp') IS NOT NULL DROP TABLE #tmp
go
CREATE TABLE #tmp ( your_xml NVARCHAR(MAX) )
GO
--insert data
INSERT INTO #tmp SELECT '<errors>
<error date = ''1394746874''>
<detail id = ''3342867234''>
<arg type = ''0''><![CDATA[512,107,741,184]]></arg>
<arg type = ''0''><![CDATA[274,877,906,944]]></arg>
<arg type = ''0''><![CDATA[J:\]]></arg>
<arg type = ''0''><![CDATA[TestLine.img]]></arg>
</detail>
</error>
<error date = ''1394747022''>
<detail id = ''3342867234''>
<arg type = ''0''><![CDATA[28,594,585,600]]></arg>
<arg type = ''0''><![CDATA[21,474,836,480]]></arg>
<arg type = ''0''><![CDATA[C:\Safe\]]></arg>
<arg type = ''0''><![CDATA[{BigMonster}]]></arg>
</detail>
</error>
</errors>'--END of xml
SELECT
'Record'+Convert(nvarchar(50), (ROW_NUMBER() OVER (ORDER BY x.y.value('(./detail[1]/arg)[1]', 'nvarchar(100)')))) AS [Source],
x.y.value('@date', 'nvarchar(100)') AS [Date],
x.y.value('./detail[1]/@id', 'nvarchar(100)') AS ID,
x.y.value('(./detail[1]/arg)[1]', 'nvarchar(100)') AS Detail1,
x.y.value('(./detail[1]/arg)[2]', 'nvarchar(100)') AS Detail2,
x.y.value('(./detail[1]/arg)[3]', 'nvarchar(100)') AS Detail3,
x.y.value('(./detail[1]/arg)[4]', 'nvarchar(100)') AS Detail4
FROM
(
SELECT CAST( your_xml AS XML ) AS your_xml
FROM #tmp
) t
CROSS APPLY t.your_xml.nodes('//errors/error') x(y)
基本上你使用CROSS APPLY并使用Properties.value来检索XML的值。