取树状结构的某个值下的所有记录

ContractedBlock.gif ExpandedBlockStart.gif Code
 1 protected void Button1_Click(object sender, EventArgs e)
 2ExpandedBlockStart.gifContractedBlock.gif        {
 3            string str = GetString("001");
 4            this.LinkButton1.Text = str;
 5        }

 6
 7        private DataSet getDataSet(string selectSQL)
 8ExpandedBlockStart.gifContractedBlock.gif        {
 9            string connectString = "Data Source=.;Initial Catalog=Test;Integrated Security=True";
10
11            DataSet ds = new DataSet();
12            using (SqlConnection conn = new SqlConnection(connectString))
13ExpandedSubBlockStart.gifContractedSubBlock.gif            {
14                SqlCommand cmd = new SqlCommand(selectSQL, conn);
15                using (SqlDataAdapter ada = new SqlDataAdapter(cmd))
16ExpandedSubBlockStart.gifContractedSubBlock.gif                {
17                    ada.Fill(ds);
18                }

19
20            }

21            return ds;
22
23        }

24
25        string allIds = string.Empty;
26        private string GetString(string Ids)
27ExpandedBlockStart.gifContractedBlock.gif        {
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)
32ExpandedSubBlockStart.gifContractedSubBlock.gif            {
33                Ids = string.Empty;
34                foreach (DataRow row in ds.Tables[0].Rows)
35ExpandedSubBlockStart.gifContractedSubBlock.gif                {
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型。

 

转载于:https://www.cnblogs.com/mishy/archive/2009/06/24/1509843.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值