【发布时间】:2010-01-13 13:23:29
【问题描述】:
我对 SQL 服务器“选择 XML 路径”查询相当有经验,但现在我遇到了一个奇怪的问题。
以下查询工作正常:
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 吗?
非常感谢。
【问题讨论】:
标签: sql-server xml sql-server-2005 subquery for-xml-path