如果我有类似的代码:
SELECT FullName, Country, OrderId, OrderDate, SaleAmount
FROM Orders
JOIN Customers ON Orders.CustomerId = Customers.CustomerId
WHERE Customers.CustomerId = 12345
FOR XML AUTO
它产生了以下内容:
<Customers FullName="Bob" Country="Canada">
<Orders OrderId="1" OrderDate="2014-02-02" SaleAmount="1000.00"/>
<Orders OrderId="2" OrderDate="2014-06-08" SaleAmouont="450.00"/>
</Customers>
但是,如果我想生成如下的XML,那该怎么办?
<Orders OrderId="1" OrderDate="2014-02-02" SaleAmount="1000.00">
<Customers FullName=.../>
</Orders>
我需要改变什么?
答案 0 :(得分:0)
CREATE TABLE Customers(CustomerID INT, FullName VARCHAR(20), Country VARCHAR(20))
GO
INSERT INTO Customers VALUES
(1, 'Bob', 'Canada')
GO
CREATE TABLE Orders(CustomerID INT, OrderID INT, OrderDate DATE, SalesAmount INT)
GO
INSERT INTO Orders VALUES
(1, 1, '20140202' , 1000),(1, 2, '20140608' , 450)
GO
SELECT OrderId, OrderDate, SalesAmount
,(SELECT FullName [@FullName]
, Country [@Country]
FROM Customers
WHERE Orders.CustomerId = Customers.CustomerId
FOR XML PATH('Customers'), TYPE)
FROM Orders
FOR XML AUTO
<Orders OrderId="1" OrderDate="2014-02-02" SalesAmount="1000">
<Customers FullName="Bob" Country="Canada" />
</Orders>
<Orders OrderId="2" OrderDate="2014-06-08" SalesAmount="450">
<Customers FullName="Bob" Country="Canada" />
</Orders>