2010-05-26 7 views
0

나는 두 테이블SQL2k8 T-SQL : XML 파일로 출력

테이블 이름이 있습니다 그래프

UID1 UID2 
----------- 
12  23 
12  32 
41  51 
32  41 

표 이름 :

NodeID UID Name 
----------------- 
1  12 Robs 
2  23 Jones 
3  32 Lim 
4  41 Teo 
5  51 Zacks 

내가 좋아하는 xml 파일을 얻으려면 프로파일 이 :

<graph directed="0"> 
    <node id="1"> 
    <att name="UID" value="12"/> 
    <att name="Name" value="Robs"/> 
    </node> 
    <node id="2"> 
    <att name="UID" value="23"/> 
    <att name="Name" value="Jones"/> 
    </node> 
    <node id="3"> 
    <att name="UID" value="32"/> 
    <att name="Name" value="Lim"/> 
    </node> 
    <node id="4"> 
    <att name="UID" value="41"/> 
    <att name="Name" value="Teo"/> 
    </node> 
    <node id="5"> 
    <att name="UID" value="51"/> 
    <att name="Name" value="Zacks"/> 
    </node> 
    <edge source="12" target="23" /> 
    <edge source="12" target="32" /> 
    <edge source="41" target="51" /> 
    <edge source="32" target="41" /> 
</graph> 

대단히 감사합니다. !

+2

을 무엇 표 1 및 XML 출력 사이의 연결? –

+0

은 XML 파일 맨 아래에서 사용됩니다. 그래프 uid1/uid2는 프로파일 테이블 – super9

답변

1

union을 사용하여 다른 노드를 결합 할 수 있습니다. 이것은 매우 복잡 않습니다

select p.nodeid as 'node/@id' 
,  (
     select [@name], [@value] 
     from (
       select 'UID' as '@name' 
       ,  cast(uid as varchar(10)) as '@value' 
       ,  nodeid 
       from @profiles 
       union all 
       select 'Name' as '@name' 
       ,  name as '@value' 
       ,  nodeid 
       from @profiles 
       ) sub 
     where sub.nodeid = p.nodeid 
     for xml path('att'), type 
     ) as node 
,  null as 'edge/@source' 
,  null as 'edge/@target' 
from @profiles p 
union all 
select null as 'node/@node' 
,  null as node 
,  g.uid1 as 'edge/@source' 
,  g.uid2 as 'edge/@target' 
from @graph g 
for xml path(''), root('graph'), type 

테스트 데이터 :

declare @graph table (uid1 int, uid2 int) 
declare @profiles table (nodeid int, uid int, name varchar(25)) 

insert into @graph values (12, 23), (12,32), (41,51), (32,41) 
insert into @profiles values (1,12,'Robs'), (2,23,'Jones'), (3,32,'Lim'), 
    (4,41,'Teo'), (5,51,'Zacks') 
+0

의 uid에 해당하지만 닫히지는 않습니다. super9

+0

@Nai : 네가 맞아, 대답 편집 됨 – Andomar

+0

감사합니다. 기이! 꽤 오랫동안 그것을 꼼짝 않고 바라 보았다고해도 나는 이것을 얻을 수있는 방법이 없었기 때문에 매우 기뻤습니다. – super9