我試圖解析XML列,並試圖通過節點的多個子節點做兩件事情的SQL Server 2012:解析XML,然後挑選一個子節點以及CONCAT所有子節點
- 迭代,並挑選一個節點基於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,不爲空。 此外,位置應該是「紐約,特區」不只是紐約。
我真的很感謝任何幫助你可以提供實現的結果。 謝謝
這是一個很好的問題:Copy'n'pasteable測試場景,自己的努力,錯誤的輸出,預期輸出。 +1從我身邊 – Shnugo
@Shnugo,謝謝! – sch