我在SQL中有以下XML:
DECLARE @xml XML
SET @xml = '<?xml version="1.0" encoding="UTF-8"?>
<BillingAddresses>
<BillingAddress Winner="W1">
<Losers>
<Loser Id="L1" />
<Loser Id="L2" />
<Loser Id="L3" />
</Losers>
</BillingAddress>
<BillingAddress Winner="W10">
<Losers>
<Loser Id="L65" />
</Losers>
</BillingAddress>
</BillingAddresses>'
我想以下列方式获取数据。
Winner | LoserID
W1 L1
W1 L2
W1 L3
W10 L65
我可以使用BillingAddress的Winner属性:
SELECT Col.value('(@Winner)[1]', 'varchar(30)')
FROM @xml.nodes('/BillingAddresses/BillingAddress') Rev(Col)
但我不知道如何获得失败者节点的Id属性
答案 0 :(得分:2)
尝试以下查询:
SELECT w.XmlCol.value('(@Winner)[1]', 'VARCHAR(50)') AS Winner,
l.XmlCol.value('(@Id)[1]', 'VARCHAR(50)') AS Loser_Id
FROM @xml.nodes('BillingAddresses/BillingAddress') w(XmlCol)
CROSS APPLY w.XmlCol.nodes('./Losers/Loser') l(XmlCol)
答案 1 :(得分:0)
我实际上得到了它......
SELECT
Col.value('(../../@Winner)[1]', 'varchar(30)') AS WinnerId
,Col.value('(@Id)[1]', 'varchar(18)') AS LoserId
FROM @xml.nodes('/BillingAddresses/BillingAddress/Losers/Loser') Rev(Col)
诀窍是深入到XML层次结构中,然后使用相对运算符(../)来获取你需要的任何父元素。