我對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?
非常感謝你。