在一个软件里编辑只能控制WHERE部分,但条件涉及递归怎么做呢?
现在在一个软件里操作,这里只能输入 sql语句的where部分
如 select * from tabA where ... order by ..
能控制的就是 where后面的部分
有个表A有栏位id deptid parentid等 这个是部门表,deptid是当前部门id,parentid是上级部门id
在另一个表B里 有deptid 这个栏位
现在 查询B表,条件是 deptid='A1'
由于A1下面有很多子部门 A2,A3,A4,呈树形,如一个人是A4部门,A4部门属于A3部门,A3属于A2,A2属于A1,
现在的需求是 如果deptid等于 A4或者A1的子部门,也能符合deptid='A1'这个条件。
求助~
[解决办法]
- SQL code
哦,需要 利用一个化树为平板的子查询作为 条件where deptid in (select parentid from (subq) where deptid='A1') or deptid='A1'subq=with t as (select a.parentid,a.deptidfrom tbA aunion allselectb.parentid,a.deptidfrom t ainner join tbA b on a.parentid=b.deptid)
[解决办法]
- SQL code
if object_id('tempdb..#T') is not null drop table #Tselect * into #T from(select deptid='A1',parentid='' union select deptid='A2',parentid='A1' union select deptid='A3',parentid='A2' unionselect deptid='A4',parentid='A3' )t;with cte as( select deptid,parentid,cd=cast(right('0000'+deptid,4)as varchar(1000)) from #t where parentid='' union all select a.deptid,a.parentid,cd=cast(cte.cd+right('0000'+a.deptid,4) as varchar(1000)) from #t a inner join cte on a.parentid=cte.deptid)select * from cte where cd like '00A1%'