【问题标题】:SQL2k8 T-SQL: Output into XML fileSQL2k8 T-SQL:输出到 XML 文件
【发布时间】:2010-05-26 18:30:05
【问题描述】:

我有两张桌子

表名:图表

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>

非常感谢!

【问题讨论】:

  • 表1和XML输出有什么联系?
  • 它在 XML 文件的底部使用。图uid1/uid2对应profiles表中的uid

标签: sql-server xml tsql sql-server-2008


【解决方案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')

【讨论】:

  • 关闭但不完全。我得到 而不是
  • 谢谢。奇妙!我很高兴我问了这个问题,因为即使盯着它看了很长时间,我也不可能得到这个。
猜你喜欢
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 2016-01-07
  • 1970-01-01
  • 2012-02-23
  • 1970-01-01
  • 2019-10-11
相关资源
最近更新 更多