T-SQL问题:查询到XML

时间:2010-03-09 10:59:35

标签: sql tsql

任何人都可以告诉我如何从这些数据中生成

------------------------DATA--------------------------

Key ParentKey
5 NULL
25 5
33 25
26 5
27 5
34 27
28 5
29 5

这个XML结果?

---------------------RESULTS--------------------------

    <record key="5" parentkey = "">
     <record key="25" parentkey = "5">
      <record key="33" parentkey = "25"></record>
      </record>
     </record>
     <record key="25" parentkey = "5">
     <record key="26" parentkey = "5">
     <record key="27" parentkey = "5">
      <record key="34" parentkey = "27"></record>
      </record>
     </record>
     <record key="28" parentkey = "5">
     <record key="29" parentkey = "5">
    </record>

2 个答案:

答案 0 :(得分:2)

您可以使用FOR XML的PATH模式构建任何XML。

在这种情况下,如果您需要2个级别:

select 
    [Key] as "@key", 
    '' as "@parentkey",
    (select 
        [Key] as "@key", 
        [ParentKey] as "@parentkey"
     from KEY_TABLE t1
     where [ParentKey] = t.[Key]
     for xml path('record'), type)
from KEY_TABLE t
where [ParentKey] is null
for xml path ('record')

对于3个级别,您需要再写一个子查询,例如:

select 
    [Key] as "@key", 
    '' as "@parentkey",
    (select 
        [Key] as "@key", 
        [ParentKey] as "@parentkey",
        (select 
            [Key] as "@key", 
            [ParentKey] as "@parentkey"
         from KEY_TABLE t2
         where [ParentKey] = t1.[Key]
         for xml path('record'), type)
     from KEY_TABLE t1
     where [ParentKey] = t.[Key]
     for xml path('record'), type)
from KEY_TABLE t
where [ParentKey] is null
for xml path ('record')

应该这样做。


子查询可以很容易地重构为递归函数:

create function SelectChild(@key as int)
returns xml
begin
    return (
        select 
            [Key] as "@key", 
            [ParentKey] as "@parentkey",
            dbo.SelectChild([Key])
        from KEY_TABLE
        where [ParentKey] = @key
        for xml path('record'), type
    )
end

然后,您可以通过

获得所需内容
select 
    [Key] as "@key", 
    '' as "@parentkey",
    dbo.SelectChild([Key])
from KEY_TABLE
where [ParentKey] is null
for xml path ('record')

答案 1 :(得分:0)

select 1 AS TAG, record AS [key!1!parentkey] from table_keys FOR XML EXPLICIT

应该这样做。