SQL 递归查询示例.doc
文本预览下载声明
SQL 递归查询示例:create table #EnterPrise (? Department nvarchar(50),--部门名称? ParentDept nvarchar(50),--上级部门? DepartManage nvarchar(30)--部门经理)insert into #EnterPrise select 技术部,总经办,Tominsert into #EnterPrise select 商务部,总经办,Jeffryinsert into #EnterPrise select 商务一部,商务部,ViViinsert into #EnterPrise select 商务二部,商务部,Peterinsert into #EnterPrise select 程序组,技术部,GiGiinsert into #EnterPrise select 设计组,技术部,yoyoinsert into #EnterPrise select 专项组,程序组,Yueinsert into #EnterPrise select 总经办,,Boss--查询部门经理是Tom的下面的部门名称;with hgo as(?? select *,0 as rank from #EnterPrise where DepartManage=Tom?? union all?? select h.*,h1.rank+1 from #EnterPrise h join hgo h1 on h.ParentDept=h1.Department)select * from hgo/*Department?????????? ParentDept??????????????? DepartManage????? rank--------------- -------------------- ----------------------- -----------技术部?????????????? 总经办??????????????????? Tom?????????????? 0程序组?????????????? 技术部??????????????????? GiGi????????????? 1设计组?????????????? 技术部??????????????????? yoyo????????????? 1专项组?????????????? 程序组??????????????????? Yue?????????????? 2*/--查询部门经理是GiGi的上级部门名称;with hgo as(?? select *,0 as rank from #EnterPrise where DepartManage=GiGi?? union all?? select h.*,h1.rank+1 from #EnterPrise h join hgo h1 on h.Department=h1.ParentDept)select * from hgo/*Department?????????????? ParentDept????????? DepartManage??? rank-------------------- ----------------------? -----------? -----------程序组?????????????????? 技术部???????????????? GiGi?????????? 0技术部?????????????????? 总经办???????????????? Tom??????????? 1总经办????????????????????????????????????????? Boss?????????? 2*/--===========================================================================================================create table #tt(id int,parentid int,name varchar(20))insert #ttselect 1,0,上海市union allselect 2,1,虹口区union allselect 3,1,徐汇区union allselect 4,1,浦东新区union allselect 5,2,江湾镇union allselect 6,2,虹口足球场union allselect 7,5,吉买盛union allselect 8,
显示全部