gpt4 book ai didi

sql - 如何在 SQL Server 中将 XML 文件读入表格格式

转载 作者:数据小太阳 更新时间:2023-10-29 03:00:37 26 4
gpt4 key购买 nike

我通过不同的搜索找到了许多类似的帖子,其中给出了将 XML 转换为表格格式的解决方案。下面是我附加的单行列的示例数据,也是我到目前为止所做的基本查询。

<DS_systeminfo>
<Systeminfo>
<Property>CurrentLanguage</Property>
<Property_value>en-US</Property_value>
</Systeminfo>
<Systeminfo>
<Property>Manufacturer</Property>
<Property_value>LENOVO</Property_value>
</Systeminfo>
<Systeminfo>
<Property>SerialNumber</Property>
<Property_value>789654</Property_value>
</Systeminfo>
<Systeminfo>
<Property>Caption</Property>
<Property_value>ATTT</Property_value>
</Systeminfo>
<Property>Manufacturer</Property>
<Property_value>LENOVO</Property_value>
</Systeminfo>
<Systeminfo>
<Property>WindowsDirectory</Property>
<Property_value>C:\WINDOWS</Property_value>
</Systeminfo>

查询如下:

SELECT SerialNumber, 
Cast(SystemInfoXML AS XML).value('(/DS_systeminfo/Systeminfo/Property)[1]', 'varchar(100)') AS Caption,
Cast(SystemInfoXML AS XML).value('(/DS_systeminfo/Systeminfo/Property_value)[1]', 'varchar(100)') AS Value
FROM TerminalsDetail

这仅获取第一个节点的值,我想在单个查询中动态选择所有节点,可能会使用 cursor

给定的数据是单行的,我有超过 100 行需要转换为表格格式。

任何类型的建议都会有所帮助。

最佳答案

Declare @YourTable table (ID int,SystemInfoXML xml)
Insert Into @YourTable values
(1,'<DS_systeminfo><Systeminfo><Property>CurrentLanguage</Property><Property_value>en-US</Property_value></Systeminfo><Systeminfo><Property>Manufacturer</Property><Property_value>LENOVO</Property_value></Systeminfo><Systeminfo><Property>SerialNumber</Property><Property_value>789654</Property_value></Systeminfo><Systeminfo><Property>Caption</Property><Property_value>ATTT</Property_value></Systeminfo><Systeminfo><Property>Manufacturer</Property><Property_value>LENOVO</Property_value></Systeminfo><Systeminfo><Property>WindowsDirectory</Property><Property_value>C:\WINDOWS</Property_value></Systeminfo></DS_systeminfo>')

Select A.ID
,B.*
From @YourTable A
Cross Apply (
Select [Caption] = f.n.value('(Property)[1]','varchar(50)')
,[Value] = f.n.value('(Property_value)[1]','varchar(50)')
From A.SystemInfoXML.nodes('DS_systeminfo') t(n)
Cross Apply t.n.nodes('Systeminfo') f(n)
) B

返回

ID  Caption           Value
1 CurrentLanguage en-US
1 Manufacturer LENOVO
1 SerialNumber 789654
1 Caption ATTT
1 Manufacturer LENOVO
1 WindowsDirectory C:\WINDOWS

关于sql - 如何在 SQL Server 中将 XML 文件读入表格格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42937556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com