【问题标题】:T-SQL Question : Query to XMLT-SQL 问题:查询到 XML
【发布时间】:2010-05-17 10:53:27
【问题描述】:

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

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

【问题讨论】:

    标签: sql tsql


    【解决方案1】:

    您可以使用 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')
    

    【讨论】:

    • 谢谢,但这行不通,该表不限于三个级别,我不想一遍又一遍地编写子查询,那是行不通的。
    • 我不同意。最后一个递归函数非常适合无限的树深度。非常感谢!
    【解决方案2】:
    select 1 AS TAG, record AS [key!1!parentkey] from table_keys FOR XML EXPLICIT
    

    应该这样做。

    【讨论】:

    • 它说缺少一个数据列
    • 您能否进一步详细说明“for xml explicit”?
    • 好的,看来我必须为我得到的每个级别/深度做一个联合。我需要它是动态的,深度/级别是无限的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 2021-12-05
    • 1970-01-01
    • 2011-05-21
    • 2013-12-18
    相关资源
    最近更新 更多