这是更详细的FOR XML EXPLICIT
类型
CREATE TABLE #Customers (
ID INT
, Name VARCHAR(100)
, City VARCHAR(100)
)
CREATE TABLE #Projects (
ID INT
, Name VARCHAR(100)
, Customer_ID INT
)
INSERT #Customers
SELECT 1, 'john', 'Mumbai' UNION ALL
SELECT 2, 'Rocky', 'Delhi' UNION ALL
SELECT 3, 'Stan', 'New York' --UNION ALL
INSERT #Projects
SELECT 1, 'pqr', 1 UNION ALL
SELECT 2, 'abc', 2 UNION ALL
SELECT 3, 'lmn', 2
SELECT h.Tag
, h.Parent
, NULL AS [Customer!1]
, c.Name AS [Name!1000]
, c.City AS [City!2000]
, NULL AS [Projects!3000]
, NULL AS [Project!3100]
, p.Name AS [Project_Name!3110]
FROM (
SELECT NULL, 1 UNION ALL
SELECT 1, 1000 UNION ALL
SELECT 1, 2000 UNION ALL
SELECT 1, 3000 UNION ALL
SELECT 3000, 3100 UNION ALL
SELECT 3100, 3110 --UNION ALL
) h(Parent, Tag)
LEFT JOIN (
SELECT 1 AS FirstTag
, 3000 AS LastTag
, c.*
FROM #Customers c
) c
ON h.Tag BETWEEN c.FirstTag AND c.LastTag
LEFT JOIN (
SELECT 3100 AS FirstTag
, 3110 AS LastTag
, c.Name AS CustomerName
, p.Name
FROM #Customers c
JOIN #Projects p
ON c.ID = p.Customer_ID
) p
ON h.Tag BETWEEN p.FirstTag AND p.LastTag
ORDER BY COALESCE(p.CustomerName, c.Name), p.Name, h.Tag
FOR XML EXPLICIT
DROP TABLE #Customers, #Projects
产生这个
<Customer>
<Name>john</Name>
<City>Mumbai</City>
<Projects>
<Project>
<Project_Name>pqr</Project_Name>
</Project>
</Projects>
</Customer>
<Customer>
<Name>Rocky</Name>
<City>Delhi</City>
<Projects>
<Project>
<Project_Name>abc</Project_Name>
</Project>
<Project>
<Project_Name>lmn</Project_Name>
</Project>
</Projects>
</Customer>
<Customer>
<Name>Stan</Name>
<City>New York</City>
<Projects />
</Customer>
请注意,这与您的原始请求不同:下面Projects
有单独Project
的 s 包装项目名称。这也适用于 sql2000。