1

如何将以下 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)

提前致谢。

4

2 回答 2

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
于 2013-09-23T23:30:05.180 回答
0

实际上,通常使用 将 XML 从父级分解到子级会更快apply,如下所示:

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

于 2013-09-25T19:07:25.737 回答