[edit]:添加了RAW测试和更好的示例代码
我需要为运行SQL Server 2005的遗留应用程序生成XML,我希望使用FOR XML
函数。
我在下面创建了一些测试数据。
我得到的结果(自动):
<n id="1" Name="test1">
<s SubName="sub1" />
<s SubName="sub2" />
</n>
<n id="2" Name="test2">
<s />
</n>
我得到的结果(RAW):
<row id="1" Name="test1" SubName="sub1" />
<row id="1" Name="test1" SubName="sub2" />
<row id="2" Name="test2" />
我想要的结果:
<n id="1" Name="test1">
<s SubName="sub1" />
<s SubName="sub2" />
</n>
<n id="2" Name="test2" />
测试代码:
IF OBJECT_ID('tempdb..#name') IS NOT NULL BEGIN DROP TABLE #name END
SELECT * INTO #name FROM (
SELECT 1 id, 'test1' Name UNION ALL
SELECT 2 id, 'test2' Name )t
IF OBJECT_ID('tempdb..#sub') IS NOT NULL BEGIN DROP TABLE #sub END
SELECT * INTO #sub FROM (
SELECT 1 id, 'sub1' SubName UNION ALL
SELECT 1 id, 'sub2' SubName )t
SELECT n.id
, n.Name
, s.SubName
FROM #name n
LEFT OUTER JOIN #sub s ON s.id = n.id
FOR XML AUTO
SELECT n.id
, n.Name
, s.SubName
FROM #name n
LEFT OUTER JOIN #sub s ON s.id = n.id
FOR XML RAW
答案 0 :(得分:4)
似乎子查询与PATH或RAW结合是一个简单的答案。两者都可以产生预期的结果:
路径:
ssh -vvv gitosis@gitosis_host
RAW:
SELECT n.id "@id"
, n.Name "@Name"
, (SELECT s.SubName "@SubName"
FROM #sub s WHERE s.id = n.id
FOR XML PATH('s'), TYPE
)
FROM #name n
FOR XML PATH('n')
答案 1 :(得分:0)
@Kesse,检查XML RAW
SELECT n.id
, n.Name
, s.SubName FROM #name n
LEFT OUTER JOIN #sub s ON s.id = n.id
FOR XML RAW