这是我第一次从SQL Server中的XML列查询,我接近实现了我想要的结果。
但是我想要帮助,因为我想要的元素和属性 - 我成功获取属性,但是元素被合并为一行而不是将它们分成不同的行。
DB中的XML记录示例:
<Attributes>
<Map>
<entry key="name" value="John Doe" />
<entry key="department" value="Finance" />
<entry key="employeeNumber" value="123456" />
<entry key="phone">
<value>
<List>
<String>TBA</String>
</List>
</value>
</entry>
<entry key="OrgStructure">
<value>
<List>
<String>top</String>
<String>person</String>
<String>organizationalPerson</String>
<String>user</String>
</List>
</value>
</entry>
<entry key="Membership">
<value>
<List>
<String>Group1</String>
<String>Group2</String>
<String>Group3</String>
</List>
</value>
</entry>
</Map>
</Attributes>
SQL查询:
SELECT
m.c.value('@key', 'varchar(max)') as xmlkey,
m.c.value('@value', 'varchar(max)') as xmlvalue,
m.c.value('.', 'varchar(max)') as xmlString
from #TEMPDB as s
cross apply s.attributes.nodes('Attributes/Map/entry') as m(c)
结果:
xmlkey xmlvalue xmlString
name John Doe
department Finance
employeeNumber 123456
phone NULL TBA
OrgStructure NULL toppersonorganizationalPersonuser
Membership NULL Group1Group2Group3
期望的结果:
xmlkey xmlvalue xmlString
name John Doe
department Finance
employeeNumber 123456
phone NULL TBA
OrgStructure NULL top
OrgStructure NULL person
OrgStructure NULL organizationalPerson
OrgStructure NULL user
Membership NULL Group1
Membership NULL Group2
Membership NULL Group3
我将不胜感激。谢谢!
答案 0 :(得分:1)
试试这样:
SELECT
m.c.value('@key', 'varchar(max)') as xmlkey,
m.c.value('@value', 'varchar(max)') as xmlvalue,
n.s.value('text()[1]','nvarchar(max)') AS ListValue
from #TEMPAK2 as s
cross apply s.attributes.nodes('Attributes/Map/entry') as m(c)
outer apply m.c.nodes('value/List/String') AS n(s);
我假设你有两种<entry>
<value>
元素看起来<value>
元素的<List>
结构的 <String>
。至少在所有情况下你都会告诉我们。