SQL XML 嵌套查询
如何根据这样的查询生成下面类似的XML?
SELECT
t1.Code,
(SELECT
CASE
WHEN t1.Type = 5 THEN
(SELECT top 1
t2.CodeName
FROM dbo.Table2 t2
WHERE t2.Id = t4.Id
FOR XML PATH('Code'), TYPE)
ELSE
(SELECT
t3.CodeName
FROM dbo.Table3 t3
WHERE t3.Id = t4.Id
FOR XML PATH('Code'), TYPE)
END
FROM dbo.Table4 t4
WHERE t4.Id = t1.Id
FOR XML PATH('CodeNames'), TYPE)
FROM dbo.Table1 t1 WITH (NOLOCK)
FOR XML RAW ('Table1Child'), TYPE, ROOT('Table1Root')
预期产出
<Table1Root>
<Table1Child Code="ABC">
<CodeNames>
<Code Name="A1" />
<Code Name="B2" />
<Code Name="C3" />
</CodeNames>
</Table1Child>
<Table1Child Code="DEF">
<CodeNames>
<Code Name="D4" />
<Code Name="E5" />
<Code Name="F6" />
</CodeNames>
</Table1Child>
</Table1Root>
How to generate below like XML based on such query?
SELECT
t1.Code,
(SELECT
CASE
WHEN t1.Type = 5 THEN
(SELECT top 1
t2.CodeName
FROM dbo.Table2 t2
WHERE t2.Id = t4.Id
FOR XML PATH('Code'), TYPE)
ELSE
(SELECT
t3.CodeName
FROM dbo.Table3 t3
WHERE t3.Id = t4.Id
FOR XML PATH('Code'), TYPE)
END
FROM dbo.Table4 t4
WHERE t4.Id = t1.Id
FOR XML PATH('CodeNames'), TYPE)
FROM dbo.Table1 t1 WITH (NOLOCK)
FOR XML RAW ('Table1Child'), TYPE, ROOT('Table1Root')
Expected output
<Table1Root>
<Table1Child Code="ABC">
<CodeNames>
<Code Name="A1" />
<Code Name="B2" />
<Code Name="C3" />
</CodeNames>
</Table1Child>
<Table1Child Code="DEF">
<CodeNames>
<Code Name="D4" />
<Code Name="E5" />
<Code Name="F6" />
</CodeNames>
</Table1Child>
</Table1Root>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
UNION
而不是CASE
并使用@
创建属性。看来您实际上不需要使用
Table4
。Do a
UNION
instead ofCASE
and use@
to create an attribute.It looks like you actually don't need to use
Table4
.