虽然这可以返回正确的结果,
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>
答案 0 :(得分:1)
你在找这样的东西吗?
declare @T table
(
KeyColumn int,
Col1 varchar(10),
Col2 varchar(10)
)
insert into @T values(1, 'Col1', 'Col2')
select (
select KeyColumn,
Col1
from @T
for xml path('Query1'), type
),
(
select KeyColumn,
Col2
from @T
for xml path('Query2'), type
)
for xml path('root')
结果:
<root>
<Query1>
<KeyColumn>1</KeyColumn>
<Col1>Col1</Col1>
</Query1>
<Query2>
<KeyColumn>1</KeyColumn>
<Col2>Col2</Col2>
</Query2>
</root>
答案 1 :(得分:0)
你无法做你想做的事。 UNION使用第一个SELECT语句中的列名和联合第二个(和后续)SELECT列中的列。换句话说,第一个SELECT命名列,后面的SELECT只被认为是这些列的附加行。
如果需要单独的列名,请改用JOINS或多表SELECT。