1
protected void Button1_Click(object sender, EventArgs e)2

{3
string str = GetString("001");4
this.LinkButton1.Text = str;5
}6

7
private DataSet getDataSet(string selectSQL)8

{9
string connectString = "Data Source=.;Initial Catalog=Test;Integrated Security=True";10

11
DataSet ds = new DataSet();12
using (SqlConnection conn = new SqlConnection(connectString))13

{14
SqlCommand cmd = new SqlCommand(selectSQL, conn);15
using (SqlDataAdapter ada = new SqlDataAdapter(cmd))16

{17
ada.Fill(ds);18
}19

20
}21
return ds;22

23
}24

25
string allIds = string.Empty;26
private string GetString(string Ids)27

{28
string select = "select Id from tree where charindex(','+parentId+',','," + Ids + ",')>0";29

30
DataSet ds = getDataSet(select);31
if (ds.Tables[0].Rows.Count > 0)32

{33
Ids = string.Empty;34
foreach (DataRow row in ds.Tables[0].Rows)35

{36
allIds += "," + row["Id"].ToString();37
Ids += "," + row["Id"].ToString();38
}39
GetString(Ids);40
}41
return allIds;42
}取出来的结果是Id,Id,Id这样规则的string。
再使用charindex()>0就可以取出所有的值。数据库中的字段ID,和parentId.就是父子关系。
0011,001
0012,001
0013,001
0011-1,0011
0011-2,0011
0011-21,0011-2
这样的数据结构就可以取出来。不过字段不能定义成nchar型。