0

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

非常感谢你。

4

2 回答 2

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')
于 2010-01-13T16:05:46.817 回答
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')
于 2010-01-22T00:09:56.170 回答