【发布时间】:2016-11-28 20:25:19
【问题描述】:
我正在尝试解析 XML 列并尝试做两件事
- 遍历节点的多个子节点并根据 1/0 标志值选择一个节点。
- 组合所有子节点以创建一个组合字段(分隔)
可运行代码块 - SQL Server 2012:
create table #temp (XMLData xml)
insert into #temp (XMLData)
values ('
<Report_Data>
<Report_Entry>
<IsActive>1</IsActive>
<PID>111</PID>
<Languages>
<Language>German</Language>
<speak>Y</speak>
<read>Y</read>
<write>Y</write>
</Languages>
<Languages>
<Language>Spanish</Language>
<speak>Y</speak>
<read>N</read>
<write>N</write>
</Languages>
<phone>
<PhoneNumber>(101)111-1111</PhoneNumber>
<PhoneType>Work</PhoneType>
<IsPrimary>1</IsPrimary>
</phone>
<phone>
<PhoneNumber>(101)111-2222</PhoneNumber>
<PhoneType>Mobile</PhoneType>
<IsPrimary>0</IsPrimary>
</phone>
</Report_Entry>
<Report_Entry>
<IsActive>1</IsActive>
<PID>222</PID>
<phone>
<PhoneNumber>(101)222-1111</PhoneNumber>
<PhoneType>Mobile</PhoneType>
<IsPrimary>0</IsPrimary>
</phone>
</Report_Entry>
<Report_Entry>
<IsActive>1</IsActive>
<PID>333</PID>
<phone>
<PhoneNumber>(101)333-1111</PhoneNumber>
<PhoneType>Phone</PhoneType>
<IsPrimary>0</IsPrimary>
</phone>
<phone>
<PhoneNumber>(101)333-2222</PhoneNumber>
<PhoneType>Mobile</PhoneType>
<IsPrimary>1</IsPrimary>
</phone>
<location>
<location-state>NY</location-state>
</location>
<location>
<location-state>DC</location-state>
</location>
</Report_Entry>
</Report_Data>
')
select
c.value('IsActive[1]','varchar(1)') as IsActive
, c.value('PID[1]','varchar(5)') as PID
, case when c.value('phone[1]/IsPrimary[1]','int') = 1 then c.value('phone[1]/PhoneNumber[1]','varchar(15)') end as PublicWorkPhone /** this condition needs to look at all sub nodes. this stops at the first one. **/
, c.value('location[1]','varchar(2)') as location
from
#temp
cross apply #temp.XMLData.nodes('/Report_Data/Report_Entry') as y(c)
drop table #temp
GO
我明白了:
IsActive PID PublicWorkPhone location
-------- ----- --------------- --------
1 111 (101)111-1111 NULL
1 222 NULL NULL
1 333 NULL NY
但是,我需要这个:
IsActive PID PublicWorkPhone location
-------- ----- --------------- --------
1 111 (101)111-1111 NULL
1 222 NULL NULL
1 333 (101)333-2222 NY,DC
对于 PID=333,主要电话是 (101)333-2222 并且不为空。 此外,位置应该是“NY,DC”,而不仅仅是 NY。
非常感谢您提供的任何帮助以实现结果。 谢谢
【问题讨论】:
-
这是个好问题:Copy'n'pasteable 测试场景,自己努力,错误输出,预期输出。从我这边 +1
-
@Shnugo,谢谢!!
标签: sql-server xml tsql xml-parsing cross-apply