循环读取数据库中可能存在的不确定层数的数据

前几天我接到了一个需求,说要让我查询某个部门及其全部子部门ID,然而子部门下有可能还有子部门,所以总共要查询几层是不确定的,经过一段时间的考虑,我用如下方法解决。

            List<int> depid = new List<int>();//存储部门ID的list
            depid.Add(deptid); //deptid是传进来的根部门id
            Hashtable repeat = new Hashtable();//用于去除重复列
            bool loop = true;//是否循环
            while (loop)
            {
                string sqlwhere1 = string.Empty;
                int depidlength = depid.Count;//得到depid的长度
                foreach (int ii in depid)
                {
                    sqlwhere1 += " '" + ii + "',";//将depid里的数据拼接为查询条件
                }
                sqlwhere1 = sqlwhere1.Substring(0, sqlwhere1.Length - 1);
                string sql1 = "select id from department where SHANGJIID in (" + sqlwhere1 + ")";
                IList<Hashtable> getid = this.FreeSQLManager.GetData(sql1);//获取查询到的数据

                foreach (Hashtable ht in getid)
                {
                    if (!repeat.ContainsKey(ht["ID"].ToString()))//去除重复列
                    {
                        repeat.Add(ht["ID"].ToString(), ht["ID"].ToString());//把不重复的列加入
                        depid.Add(int.Parse(ht["ID"].ToString()));//把不重复的列加入
                    }

                }
                if (depid.Count == depidlength)
                {
                    loop = false;//如果循环完成一次后depid的长度没有变化,证明找不到其他的子部门,循环结束
                }
            }

猜你喜欢

转载自blog.csdn.net/touhousonic/article/details/80824340
今日推荐