[英]Query from XML stored in database as nvarchar
我在表的一列中存儲了 xml 數據。 列數據類型是 nvarchar(max)。
我需要從列中查詢數據以提取一些節點信息。 下面是存儲的 xml 數據示例
<Response>
<Quote>
<ID>1</ID>
<Item>
<ItemNumber>123456</ItemNumber>
</Item>
<Price>
<LPrice>12</LPrice>
</Price>
<Stocks>
<Stock>
<Quantity>2</Quantity>
</Stock>
<Stock>
<Quantity>1</Quantity>
</Stock>
</Stocks>
</Quote>
<Quote>
<ID>2</ID>
<Item>
<ItemNumber>234121</ItemNumber>
</Item>
<Price>
<ListPrice>34</ListPrice>
</Price>
<Stocks>
<Stock>
<Quantity>4</Quantity>
</Stock>
<Stock>
<Quantity>2</Quantity>
</Stock>
</Stocks>
</Quote>
</Response>
我想以以下格式獲取信息:
項目編號 | 價格 | 數量 |
---|---|---|
123456 | 12 | 3 |
234121 | 34 | 6 |
請幫忙。
將 xml 數據存儲在 nvarchar()/varbinary() 列中非常好,因為這是保持源信息保真度的唯一方法。
declare @t table(x nvarchar(max))
insert into @t(x)
values(N'<Response>
<Quote>
<ID>1</ID>
<Item>
<ItemNumber>123456</ItemNumber>
</Item>
<Price>
<ListPrice>12</ListPrice>
</Price>
<Stocks>
<Stock>
<Quantity>2</Quantity>
</Stock>
<Stock>
<Quantity>1</Quantity>
</Stock>
</Stocks>
</Quote>
<Quote>
<ID>2</ID>
<Item>
<ItemNumber>234121</ItemNumber>
</Item>
<Price>
<ListPrice>34</ListPrice>
</Price>
<Stocks>
<Stock>
<Quantity>4</Quantity>
</Stock>
<Stock>
<Quantity>2</Quantity>
</Stock>
</Stocks>
</Quote>
</Response>');
select
n.q.value('(Item/ItemNumber/text())[1]', 'nvarchar(50)'),
n.q.value('(Price/ListPrice/text())[1]', 'nvarchar(50)'),
n.q.query('sum(Stocks/Stock/Quantity)').value('.', 'nvarchar(50)')
from @t as t
cross apply(select try_cast(t.x as xml) as xx) as c
cross apply c.xx.nodes(N'Response/Quote') as n(q);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.