2010-01-13 52 views
0

我對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?

非常感謝你。

回答

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') 
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')