2010-03-09 26 views
2

任何人都可以告訴我怎麼從這個數據T-SQL問題:查詢到XML

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

回答

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

應該這樣做。

+0

它說什麼數據列缺少 –

+0

可能你進一步闡述'for xml explicit'? – Juvil

+0

好吧,看來我得爲每級/深度我有做一個工會。我需要這是動態的,深度/水平是無限 – Juvil

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') 
+0

感謝,但是這不會工作,以及該表不侷限於最多三個級別的,我不希望通過編寫子查詢,並通過這只是不工作。 – Juvil

+1

我不同意。最後一個遞歸函數適用於無限樹深度。謝謝一堆! –