私は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を達成する方法を誰かが正しい方向に導くことができますか?
どうもありがとうございました。