SQL Server 2005では、サブ選択問題で組合とXMLパスを選択します
-
20-09-2019 - |
質問
私はむしろ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>
この私の結果声明(大きめの一部)で、私はあまりにも第二keyfieldを必要とします:
<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 keyfieldsとXMLをaccomplischする方法を正しい方向に私を置くことができますか?
あなたありがとうとてもます。
解決
あなたの副選択の問題は、最初の部分は、すべての(なしFROM-
clause)で任意のテーブルを参照していないということです。
このリストは私にあなたが要求した出力を与えます:
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')
他のヒント
ここでは簡略化した例であるが、これはあなたが必要なものを取得していますか?
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')
所属していません StackOverflow