2017-03-28 136 views
1

下面的SQL代碼的SQL Server FOR XML嵌套子選擇

SELECT 
b.GivenName [Individual/Name/FirstName] , 
b.FamilyName [Individual/Name/LastName] , 
b.Address_Country [Individual/Address/CountryCode] , 
b.AddressFree [Individual/Address/AddressFree] 
FROM dbo.stage_Clients_Merge b 
WHERE b.DWHClientNo = @dwhclientNo 
FOR XML PATH('Owner'), TYPE 

將生成一個XML片段

<Owner> 
<Individual> 
    <Name> 
    <FirstName>Bob</FirstName> 
    <LastName>Smith</LastName> 
    </Name> 
    <Address> 
    <CountryCode>US</CountryCode> 
    <AddressFree>123,Utah</AddressFree> 
    </Address> 
</Individual> 
</Owner> 

如果擴展該查詢包括子查詢返回,爲例如,使用以下方式與個人相關的所有訂單:

(SELECT 
    c.OrderIdentificationNumber [Individual/OrderNumber] 
    FROM 
    dbo.stage_Customer_Orders c 
    WHERE 
    c.CustomerNo = b.masterClient 
    FOR 
    XML PATH(''), TYPE) 

我將獲得單獨的部分兩次。我怎麼能結合這兩個返回以下?

<Owner> 
<Individual> 
    <OrderNo>12345</OrderNo> 
    <OrderNo>23456</OrderNo> 
    <Name> 
    <FirstName>Bob</FirstName> 
    <LastName>Smith</LastName> 
    </Name> 
    <Address> 
    <CountryCode>US</CountryCode> 
    <AddressFree>123,Utah</AddressFree> 
    </Address> 
</Individual> 
</Owner> 

回答

1

嘗試像這樣

我成立了一個模型方案單機版解決方案。下次你有問題時,你可以自己嘗試。這樣可以更容易地理解您的問題併爲其創建一個完整的工作和可測試的解決方案。

DECLARE @stage_Clients_Merge TABLE(ID INT,FirstName VARCHAR(100),LastName VARCHAR(100),CountryCode VARCHAR(100),AdressFree VARCHAR(100)); 
INSERT INTO @stage_Clients_Merge VALUES 
(1,'Bob','Smith','US','123/Utah') 
,(2,'Jim','Doh','US','123/Maryland'); 


DECLARE @orders TABLE(CustomerID INT, OrderNo INT) 
INSERT INTO @orders VALUES 
(1,11111),(1,12222) 
,(2,21111),(2,22222); 

SELECT (SELECT OrderNo FROM @orders WHERE CustomerID=b.ID FOR XML PATH(''),TYPE) AS Individual 
     ,FirstName AS [Individual/Name/FirstName] 
     ,LastName AS [Individual/Name/LastName] 
     ,CountryCode AS [Individual/Address/CountryCode] 
     ,AdressFree AS [Individual/Address/AdressFree] 
FROM @stage_Clients_Merge AS b 
FOR XML PATH('Owner'); 
1

您可以使用子查詢和[data()]只是沒有額外的嵌套得到的列值 - 然後使用path像以前一樣:

SELECT 
    (SELECT  c.OrderIdentificationNumber as [data()] 
    FROM dbo.stage_Customer_Orders c 
    WHERE c.CustomerNo = b.masterClient 
    For XML Path('OrderNo'), type) as [Individual], 
    b.GivenName [Individual/Name/FirstName] , 
    b.FamilyName [Individual/Name/LastName] , 
    b.Address_Country [Individual/Address/CountryCode] , 
    b.AddressFree [Individual/Address/AddressFree] 
FROM dbo.stage_Clients_Merge b 
WHERE b.DWHClientNo = @dwhclientNo 
FOR XML PATH('Owner'), TYPE 
+0

你比我快,+1 – Shnugo