如何将以下XML层次结构指定为Microsoft SQL中的可读列?
<transaction id=1>
<item id=1>
<price>1</price>
</item>
<item id=2>
<price>1</price>
</item>
</transaction>
<transaction>
<item id=1>
<price>1</price>
</item>
</transaction>
例如
select
x.i.value('(????)','Varchar(max)') [TransId]
x.i.value('(????)','Varchar(max)') [ItemId]
x.i.value('(????)','Varchar(max)') [PriceId]
from @xml.nodes('/transaction') x(i)
提前致谢。
答案 0 :(得分:1)
属性值必须始终以XML中的引号显示。 不确定所需的输出。一个例子是:
declare @xml xml
Select @xml=
'<transaction id="1">
<item id="1">
<price>1</price>
</item>
<item id="2">
<price>2</price>
</item>
</transaction>
<transaction>
<item id="1">
<price>3</price>
</item>
</transaction>'
SELECT
y.value('../@id','int') as TransactionID,
y.value('@id','int') as ItemID,
y.value('(./price/text())[1]', 'Varchar(max)') as Price
FROM @xml.nodes('/transaction/item') as x(y)
order by TransactionID,ItemID
输出:
NULL 1 3
1 1 1
1 2 2
答案 1 :(得分:0)
实际上通常使用apply
将XML从父级分解为子级更快,如下所示:
select
t.c.value('@id','int') as TransId,
i.c.value('@id','int') as ItemId,
i.c.value('(price/text())[1]', 'int') as PriceId
from @xml.nodes('transaction') as t(c)
outer apply t.c.nodes('item') as i(c)
order by TransId, ItemID
<强> sql fiddle demo 强>