2010-01-13 52 views
0

我对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?

非常感谢你。

回答

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') 
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')