资源描述:
《SQL 递归查询示例》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、SQL递归查询示例:createtable#EnterPrise( Departmentnvarchar(50),--部门名称 ParentDeptnvarchar(50),--上级部门 DepartManagenvarchar(30)--部门经理)insertinto#EnterPriseselect'技术部','总经办','Tom'insertinto#EnterPriseselect'商务部','总经办','Jeffry'insertinto#EnterPriseselect'商务一部','商务部','ViVi'insert
2、into#EnterPriseselect'商务二部','商务部','Peter'insertinto#EnterPriseselect'程序组','技术部','GiGi'insertinto#EnterPriseselect'设计组','技术部','yoyo'insertinto#EnterPriseselect'专项组','程序组','Yue'insertinto#EnterPriseselect'总经办','','Boss'--查询部门经理是Tom的下面的部门名称;withhgoas( select*,0asrankfro
3、m#EnterPrisewhereDepartManage='Tom' unionall selecth.*,h1.rank+1from#EnterPrisehjoinhgoh1onh.ParentDept=h1.Department)select*fromhgo/*Department ParentDept DepartManage rank------------------------------------------------------------------
4、---技术部 总经办 Tom 0程序组 技术部 GiGi 1设计组 技术部 yoyo 1专项组 程序组 Yue 2*/--查询部门经理是GiGi的上级部门名称;withhgoas( se
5、lect*,0asrankfrom#EnterPrisewhereDepartManage='GiGi' unionall selecth.*,h1.rank+1from#EnterPrisehjoinhgoh1onh.Department=h1.ParentDept)select*fromhgo/*Department ParentDept DepartManage rank------------------------------------------ ----------
6、- -----------程序组 技术部 GiGi 0技术部 总经办 Tom 1总经办 Boss 2*/--==================================================================================
7、=========================createtable#tt(idint,parentidint,namevarchar(20))insert#ttselect1,0,'上海市'unionallselect2,1,'虹口区'unionallselect3,1,'徐汇区'unionallselect4,1,'浦东新区'unionallselect5,2,'江湾镇'unionallselect6,2,'虹口足球场'unionallselect7,5,'吉买盛'unionallselect8,5,'易卜莲花'union
8、allselect9,5,'农工商'unionallselect10,6,'吉买盛'withcteas(select*,0aslevlfrom#ttwhereid=2unionallselecta.*,b.levl+1from#tta,ctebwh