我尝试了一个FOR XML查询,类似于字幕“FOR XML表达式嵌套”下显示的here。我的问题是我必须有三个XML元素级别。结果应该是这样的。
<StepTree Name="ALFKI">
<Step Name="Foo">
<Result id="123" />
<Result id="456" />
</Step>
<Step Name="Bar">
<Result id="789" />
<Result id="987" />
</Step>
</StepTree >
我尝试过这种类型的查询。
SELECT 1 as TAG,
NULL as Parent,
StepTrees.Name AS [StepTree!1!Name],
NULL as [Step!2!Name],
NULL as [Result!3!id]
FROM StepTrees
WHERE StepTrees.Name = 'ALFKI'
UNION ALL
SELECT 2,
1,
StepTrees.Name,
Steps.Name,
NULL
FROM Steps
JOIN StepTrees ON Steps.StepTreeId = StepTrees.Id
WHERE StepTrees.Name = 'ALFKI'
UNION ALL
SELECT DISTINCT 3,
2,
StepTrees.Name,
Steps.Name,
Results.id
FROM StepTrees
JOIN Steps ON Steps.StepTreeId = StepTrees.Id
JOIN Results ON Steps.StepId = Results.StepId
FOR XML EXPLICIT
生成的XML如下所示。
<StepTree Name="ALFKI">
<Step Name="Foo" />
<Step Name="Bar">
<Result id="123" />
<Result id="456" />
<Result id="789" />
<Result id="987" />
</Step>
</StepTree >
有什么想法吗?
答案 0 :(得分:0)
使用此查询:
SELECT 1 as TAG,
NULL as Parent,
StepTrees.Name AS [StepTree!1!Name],
NULL as [Step!2!Name],
NULL as [Result!3!id]
FROM StepTrees
WHERE StepTrees.Name = 'ALFKI'
UNION ALL
SELECT 2,
1,
Null,
Steps.Name,
NULL
FROM Steps
JOIN StepTrees ON Steps.StepTreeId = StepTrees.Id
WHERE StepTrees.Name = 'ALFKI'
UNION ALL
SELECT DISTINCT 3,
2,
Null,
Steps.Name,
Results.id
FROM StepTrees
JOIN Steps ON Steps.StepTreeId = StepTrees.Id
JOIN Results ON Steps.StepId = Results.StepId
ORDER BY [Step!2!Name],[Result!3!id]
FOR XML EXPLICIT