2010-01-13 8 views
0

SQL Server "XML 경로 선택"쿼리에 익숙하지 않지만 이상한 문제가 발생합니다.SQL Server 2005에서 하위 선택 문제로 공용 구조체가있는 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에 하위 쿼리가 추가되지 않으면 선택 목록에 하나의 식만 지정할 수 있습니다."

여러 요소가 XML 경로 마녀 결과로 하위 쿼리에 여러 레코드를 가질 수 있다는 것을 알고 있습니다. 하지만 왜 이것이 노동 조합과 함께 할 수 없는지 나는 이해하지 못한다.

누가 내 (하위) 쿼리에서 2 개의 keyfields를 사용하여 XML을 달성하는 방법을 올바른 방향으로 옮길 수 있습니까?

고맙습니다.

답변

1

subselect의 문제점은 첫 번째 부분이 전혀 테이블을 참조하지 않는다는 것입니다 (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')