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>

この(より大きな部分の)ステートメントの結果では、2番目のキーフィールドも必要です:

<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で導入されていない場合、選択リストで指定できる式は1つだけです」というエラーが表示されます。

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 に答える