很多时候我们会在数据库表中存储树结构的数据,如菜单:一级菜单.二级菜单.三级菜单... 如果树结构层次比较多,如何能够在只知道某节点的情况下,找到此节点下的所有子级数据呢? 在.NET后台可以定义一个递归函数,通过递归可以找到相应的数据. 那么在SQL中,用脚本如何递归查找呢? 在SQL2008以上版本有一个 WITH CTE AS 的用法,可以实现相应的业务.(只能使用一个with,多个CTE中间用逗号分隔) 例: -- 定义一个temp的"临时表" with temp as ( -
Linq递归查找: public IEnumerable<MenuInfo> GetTree(int id, IEnumerable<MenuInfo> lst) { var query = from c in lst where c.parent_menu_id == id select c; return query.Concat(query.SelectMany(t => GetTree(t.menu_id, lst))).ToList(); } 调用如下: int g
function cc.exports.findValueByTbl(tbl,key)--递归方法,用于查找tbl中对应的键值 for k,v in pairs(tbl) do if k == key then if type(tbl[i])=="table" then--如果是table类型,递归查找 return findValueByTbl(v,key) else return v end end end end
创建数据库 create table City(id varchar(3) primary key , pid varchar(3) , name varchar(10)) 插入数据 insert into City values('001' , null , '广东省'); insert into City values('002' , '001' , '广州市'); insert into City values('003' , '001' , '深圳市') ; insert into Ci