2016-02-07 76 views
2
 

I have table 
=========================== 
Id PlaceName  ParentId 
1  Australia  Null 
2  NSW    1 
3  Sa    1 
4  Ashfield   2 


How can I generate list like below using c# 
============================================= 
Australia 
NSW, Australia 
SA, Australia 
Ashfield, NSW, Australia 

I will appreciate for your help 

+0

因爲誰也不知道,如果艾士菲是在新南威爾士州或SA城市的方式。您還需要提供Parent表。 – numbtongue

+0

有Ashfield的父母身份證,這是NSW的Id,NSW的父母身份證是1,這又是澳大利亞的Id,因此得到了澳大利亞的Ashfield, – user1125135

+0

您正在使用哪個'RDBMS' –

回答

2

如果您RDBMS支持的RECURSIVE CTE那就試試這個

架構設置&的樣本數據

CREATE TABLE recursive_cte 
    (
    Id  INT, 
    PlaceName VARCHAR(50), 
    ParentId INT 
) 

INSERT recursive_cte 
VALUES (1,'Australia',NULL), 
     (2,'NSW',1), 
     (3,'Sa',1), 
     (4,'Ashfield',2) 

遞歸CTE查詢:

;WITH cte 
    AS (SELECT Id, 
       PlaceName, 
       ParentId, 
       Cast(PlaceName AS VARCHAR(8000)) AS Parent_name -- CAST is used to avoid type mismatch between anchor and recursive part 
     FROM recursive_cte rc 
     WHERE ParentId IS NULL 
     UNION ALL 
     SELECT rc.Id, 
       rc.PlaceName, 
       rc.ParentId, 
       Cast(rc.PlaceName + ',' + Parent_name AS VARCHAR(8000)) 
     FROM cte c 
       INNER JOIN recursive_cte rc 
         ON c.id = rc.ParentId) 
SELECT * 
FROM cte 

結果:

╔════╦═══════════╦══════════╦════════════════════════╗ 
║ Id ║ PlaceName ║ ParentId ║  Parent_name  ║ 
╠════╬═══════════╬══════════╬════════════════════════╣ 
║ 1 ║ Australia ║ NULL  ║ Australia    ║ 
║ 2 ║ NSW  ║ 1  ║ NSW,Australia   ║ 
║ 3 ║ Sa  ║ 1  ║ Sa,Australia   ║ 
║ 4 ║ Ashfield ║ 2  ║ Ashfield,NSW,Australia ║ 
╚════╩═══════════╩══════════╩════════════════════════╝ 
+0

好!在C#中,你必須使用Linq和DataTable,但爲什麼不在SQL中執行。 – numbtongue

+0

@numbtongue是的,SQL中的遞歸CTE被引入來處理分層數據,如上 –

+0

好極了!非常感謝。它真的幫了我很多。 – user1125135