首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> SQL Server 資料庫 >> 關於SqlServer

SQL Server 階層資料樹狀顯示:自定義樹結構 + 遞歸輸出完整實作 (C#)

     編輯:關於SqlServer

資料庫儲存無限級分類 (如 `ID, ParentID, Name, Depth`),前端需樹狀顯示。本文提供 C# 完整實作:定義樹節點類別、依 `Depth` 排序讀取資料構建記憶體樹、遞歸輸出 HTML `

  • ` 結構。遞歸僅在記憶體進行,效能極佳,適合一般分類選單、組織架構、商品類別。

    1. 樹節點類別定義

    public class ZoneList {
      private readonly ZoneList _parent;
      private readonly List _childs = new List();
      private readonly ZoneItem _value;
    
      public ZoneList Parent => _parent;
      public List Childs => _childs;
      public ZoneItem Value => _value;
      public ZoneList Root {
        get {
          var cur = this;
          while (cur.Parent != null) cur = cur.Parent;
          return cur;
        }
      }
      public ZoneList() { }
      public ZoneList(ZoneItem value, ZoneList parent) { _value = value; _parent = parent; }
      public ZoneList AddChild(ZoneItem value) {
        var node = new ZoneList(value, this);
        _childs.Add(node);
        return node;
      }
    }
    
    public class ZoneItem {
      public int ID { get; set; }
      public int Tree { get; set; }   // Depth/Level
      public string Name { get; set; }
    }

    2. 讀取資料庫並構建樹 (按 LID/Depth ASC)

    public ZoneList Select() {
      var root = new ZoneList();
      ZoneItem item;
      int currentDepth = 0;
    
      using (var reader = SiteSQL.ExecuteReader("ZoneSelect")) // SELECT * FROM Zone ORDER BY LID ASC
      while (reader.Read()) {
        item = new ZoneItem { ID = reader.GetInt32(0), Tree = reader.GetInt32(1), Name = reader.GetString(2) };
        int depthDiff = currentDepth - item.Tree;
        for (int i = 0; i <= depthDiff; i++) root = root.Parent; // 回溯到父層
        root = root.AddChild(item);
        currentDepth = item.Tree;
      }
      return root.Root;
    }

    關鍵:資料需按「前序遍歷順序」(父節點先於子節點,同層按順序) 排序,`Depth` 遞增表示進入子層,遞減表示返回父層。

    3. 遞歸輸出 HTML 樹狀結構

    private void ZoneOutWrite(ZoneList node) {
      foreach (var child in node.Childs) {
        Response.Write($"
  • {child.Value.Name}"); if (child.Childs.Count > 0) { Response.Write("
      "); ZoneOutWrite(child); Response.Write("
    "); } Response.Write("
  • "); } }

    頁面調用:Response.Write("

      "); ZoneOutWrite(tree.Root); Response.Write("
    ");

    適用性與限制

    • ✅ 適用:一般分類選單、組織架構、靜態商品類別 (讀多寫少)。
    • ❌ 不適用:高頻寫入的無限回覆評論、即時協作樹結構 (需 Closure Table / Materialized Path / 遞歸 CTE 等方案)。

    擴充建議

    • 資料庫層改用 WITH RECURSIVE CTE (SQL 2005+) 直接輸出巢狀 JSON/XML,減少應用層組裝。
    • 前端改用 jsTree / zTree 等元件,支援懶加載、搜尋、拖曳排序。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved