我对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>
所以我用union-select改变了我的(子)查询:
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?
非常感谢你。
答案 0 :(得分:1)
您的子选择的问题是第一部分根本没有引用任何表(没有FROM-
子句)。
此列表为我提供了您所要求的输出:
declare @mytable table (
keyfield1 nvarchar(20),
keyfield2 nvarchar(20)
)
insert into @mytable values ('Dummyvalue1', 'Dummyvalue2')
select * from @mytable
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')
select
(
select * from (
select
'Keyfield1' as "@Name",
t1.Keyfield1 as "Value"
from @MyTable t1
where
t1.KeyField1= t2.KeyField1
union all
select
'Keyfield2' as "@Name",
t3.Keyfield2 as "Value"
from @MyTable t3
where
t3.KeyField2= t2.KeyField2) a
for xml path('Field'),type, elements
) as 'Key'
from @MyTable t2
for XML path('Path') , elements XSINIL, root('Root')
答案 1 :(得分:0)
这是一个简化的示例,但这可以满足您的需求吗?
select
(
select
'Keyfield1' as "@Name",
'Blah' as "Value"
for xml path('Key'),type, elements
),
(
select
'Keyfield2' as "@Name",
'Blah' as "Value"
for xml path('Key'),type, elements
)
for XML path('Path') , elements XSINIL, root('Root')