我对SQL服务器“select for XML path”查询颇有经验,但现在我遇到了一个奇怪的问题。SQL Server 2005 select for XML path with union in sub-selection problem
下面的查询工作正常:
select
(
select
'Keyfield1' as "@Name",
t1.Keyfield1 as "Value"
from MyTable t1
where
t1.KeyField1= t2.KeyField1 and
t1.KeyField2= t2.KeyField2
for xml path('Field'),type, elements
) as 'Key'
from MyTable t2
for XML path('Path') , elements XSINIL, root('Root')
这将导致(对于虚拟数据集)在这个XML:
<Root>
<Path>
<Key Name="KeyField1">
<Value>DummyValue1</Value>
</Key>
</Path>
</Root>
在我的发言中(一个更大的一部分)的结果,我需要第二个关键字段太:
<Root>
<Path>
<Key Name="KeyField1">
<Value>DummyValue1</Value>
</Key>
<Key Name="KeyField2">
<Value>DummyValue2</Value>
</Key>
</Path>
</Root>
所以我改变了我的(子)查询与工会选择:
select
(
select
'Keyfield1' as "@Name",
t1.Keyfield1 as "Value"
union all
select
'Keyfield2' as "@Name",
t1.Keyfield2 as "Value"
from MyTable t1
where
t1.KeyField1= t2.KeyField1 and
t1.KeyField2= t2.KeyField2
for xml path('Field'),type, elements
) as 'Key'
from MyTable t2
for XML path('Path') , elements XSINIL, root('Root')
但是现在我收到错误“子查询未与EXISTS一起引入时,只能在选择列表中指定一个表达式。”
我知道有可能在一个子查询中有多个记录,XML路径会导致多个元素。但我不明白为什么这不能用工会来完成。
有人可以让我在正确的方向如何实现与我的(子)查询中的2个关键字段的XML?
非常感谢你。