//SQL 實現地區的實現樹形結構遞歸查詢(無限級分類),level爲節點層級,由小至大依次 2018-09-25 StringBuilder areaSQL = new StringBuilder(); areaSQL.AppendLine(" with cte_child(id,areaName,pid,level) as ( select id,areaName,pid,0 as level from erp_area "); areaSQL.AppendLine(" where pid = 0 "); //優先列出第一節點 id = 1 指定中國 areaSQL.AppendLine(" union all "); //遞歸條件 areaSQL.AppendLine(" select a.id,a.areaName,a.pid,b.level+1 "); areaSQL.AppendLine(" from erp_area a inner join cte_child b on ( a.pid=b.id) "); areaSQL.AppendLine(" ) select * from cte_child "); DataTable dtArea = sqlhelp.GetDataSet(areaSQL.ToString()).Tables[0];