我有一個 XML 資料集,它定義了客戶串列和客戶購買的所有產品
<Info>
<Customer CustomerId="1">
<Product Name="A" Cost="20" />
<Product Name="C" Cost="30" />
</Customer>
<Customer CustomerId="2">
<Product Name="A" Cost="23" />
<Product Name="B" Cost="46" />
</Customer>
<Customer CustomerId="3">
<Product Name="B" Cost="32" />
<Product Name="C" Cost="64" />
</Customer>
</Info>
我想在這樣的單獨查詢中列出客戶及其產品
| 顧客 | 產品 |
|---|---|
| 1 | 20 澳元,30 加元 |
| 2 | 23 美元,46 美元 |
| 3 | 32 美元,64 美元 |
作為 SQL Server 中 XQuery 的新手,我正在努力尋找解決方案。在過去的幾天里,我想出了一個看起來像這樣的查詢
declare @xml xml;
...
select
Info.Customer.value('@CustomerID[1]', 'int') as CustomerID,
Info.Customer.query('./*') as Products
from
@xml.nodes('info/Customer') Info(Customer);
產生以下結果
| 顧客 | 產品 |
|---|---|
| 1 | <Product Name="A", Cost="20" />, <Product Name="C", Cost="30" /> |
| 2 | <Product Name="A", Cost="23" />, <Product Name="B", Cost="46" /> |
| 3 | <Product Name="B", Cost="32" />, <Product Name="C", Cost="64" /> |
對于那些熟悉FOR XML使用以下模式連接行的人,我想明確指出這不是我想要的。
SELECT
CustomerId,
(
SELECT Name ' $' Cost
FROM Product
WHERE Product.CustomerId = Customer.CustomerId
FOR XML PATH(''), TYPE
)
FROM Customer
我用來生成<Info>...</Info>資料集的查詢在很短的時間內運行并且擁有我需要的所有資料,我只是想知道是否有任何方法可以以相同的方式連接屬性?
uj5u.com熱心網友回復:
正如@lptr 在評論中指出的那樣,您可以使用以下任一解決方案
declare @xml xml = N'<Info>
<Customer CustomerId="1">
<Product Name="A" Cost="20" />
<Product Name="C" Cost="30" />
</Customer>
<Customer CustomerId="2">
<Product Name="A" Cost="23" />
<Product Name="B" Cost="46" />
</Customer>
<Customer CustomerId="3">
<Product Name="B" Cost="32" />
<Product Name="C" Cost="64" />
</Customer>
</Info>';
select
i.c.value('@CustomerId', 'int'),
stuff(
i.c.query('
for $p in Product
return text{concat(", ", $p/@Name, " $", $p/@Cost)}
').value('text()[1]', 'varchar(max)'), 1, 2,''),
i.c.query('
for $p in Product
return text{concat($p/@Name, " $", $p/@Cost, if ($p is Product[last()]) then "" else ", ")}
')
from @xml.nodes('Info/Customer') as i(c);
db<>小提琴
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/452392.html
