これは正しい結果を返すように機能しますが、
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 が原因で、使用しようとしているさまざまな命名を一緒にすると結果が区別されないことです。両方を 1 つの結果セットの下に異なる名前で表示するにはどうすればよいですか? XMLでこれを行うことを考えていますが、方法がわかりませんか?
さまざまなクエリをさまざまな結果/行数と組み合わせて、すべてを 1 つの大きな 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>