ITPub博客

首页 > 应用开发 > IT综合 > SQLserver数据库中关于递归的查询使用

SQLserver数据库中关于递归的查询使用

原创 IT综合 作者:Fishwood 时间:2015-10-20 16:39:26 0 删除 编辑
度量快速开发平台数据库支持sqlserver数据库,我们之前习惯的oracle递归查询用的 start with dept_id=1000 connect by prior dept_id=upper_id的方式就不灵了。
比如我们的组织机构里面有很多下级机构及部门,要查询出登录人所在的机构,并列出该机构下所有机构和部门。Sqlserver写法如下:


 with NewTable as
(
select a.dept_id,a.dept_name,a.upper_id,a.tree_code,a.extend_type,a.DEPT_LEVEL,a.SORT_ORDER from  SA_DEPT_DICT a where a.DEPT_ID=登录用户的部门ID
union all
select b.dept_id,b.dept_name,b.upper_id,b.tree_code,b.extend_type,b.DEPT_LEVEL,b.SORT_ORDER from SA_DEPT_DICT b  inner join NewTable c on b.DEPT_ID=c.UPPER_ID
where b.dept_TYPE=2 or b.DEPT_TYPE=6
) 
,
 NewTable1 as
(
select a.dept_id,a.dept_name,a.upper_id,a.tree_code,a.extend_type,a.DEPT_LEVEL,a.SORT_ORDER from  SA_DEPT_DICT a , (select  right(MAX(tree_code),4) dept_ID from NewTable where EXTEND_TYPE='机构' ) c where a.DEPT_ID=c.dept_ID
union all
select b.dept_id,b.dept_name,b.upper_id,b.tree_code,b.extend_type,b.DEPT_LEVEL,b.SORT_ORDER from SA_DEPT_DICT b  inner join NewTable1 c on c.DEPT_ID=b.UPPER_ID
where b.dept_TYPE=2 or b.DEPT_TYPE=6
) 
select DEPT_ID,DEPT_NAME,UPPER_ID,SORT_ORDER,EXTEND_TYPE,TREE_CODE from NewTable1
原文地址:http://bbs.delit.cn/thread-153-1-1.html
转载请注明出处:
撰写人:度量科技www.delit.cn

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/328153/viewspace-1815216/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2015-09-17

  • 博文量
    184
  • 访问量
    937896