虽然这可以返回正确的结果,
SELECT r.KeyColumn as '@Key', t1.Key1 as 'Key1', t1.Col1 as 'Col1'
FROM @resultset r
INNER JOIN Table1 t1 ON t1.Col1 = 'SomeCondition'
--FOR XML PATH('Column1') -- This errors out when used with union, works as a seperate query.
UNION
SELECT r.KeyColumn as '@Key', t2.Key1 as 'Key2', t2.Col2 as 'Col2'
FROM @resultset r
INNER JOIN Table2 t2 ON t2.Col1 = 'SomeCondition2'
--FOR XML PATH('Column2') -- This errors out when used with union, works as a seperate query.
结果:
@Key Key1 Col1
1 1 Table1Col1
1 1 Table2Col
问题在于,由于 UNION 的原因,结果并不能区分我尝试使用的不同命名。如何让两者都显示在一个结果集下但名称不同?我正在考虑用 XML 来做到这一点,但我不知道怎么做?
将不同查询与不同结果/行数组合并将所有内容放在一个大 XML 下的最佳方法是什么?
好的,我能想到的最好的方法是:
SELECT r.KeyColumn as '@Key', t1.Key1 as 'Key1', t1.Col1 as 'Col1', '' as 'Key2', '' as 'Col2'
FROM @resultset r
INNER JOIN Table1 t1 ON t1.Col1 = 'SomeCondition'
--FOR XML PATH('Column1') --Error
UNION
SELECT r.KeyColumn as '@Key', '' AS 'Key1', '' as 'Col1', t2.Key1 as 'Key2', t2.Col2 as 'Col2'
FROM @resultset r
INNER JOIN Table2 t2 ON t2.Col1 = 'SomeCondition2'
--FOR XML PATH('Column2') -- Error
会给我结果(再次,正如预期的那样,因为联盟)
@Key Key1 Col1 Key2 Col2
---------------------------------------------------------------------------
1 1 Table1Col1
1 1 Table2Col
I still want to get my results as an XML thus:
<Root>
<Column1 Key="1">
<Key1>1</Key1>
<Col1>Table1Col1</Col1>
</Column1>
<Column2 Key="1">
<Key2>1</Key2>
<Col2>Tabl2Col</Col2>
</Column2>
</Root>
或以下内容:
<Root Key="1">
<Column1>
<Key1>1</Key1>
<Col1>Table1Col1</Col1>
</Column1>
<Column2>
<Key2>1</Key2>
<Col2>Tabl2Col</Col2>
</Column2>
</Root>