函数代码:create or replace function f_company_id(v_dept_id varchar2) return varchar2 iscompany_id varchar2(100);count_num number;beginselect count(0) into count_num from sys_company_dept t where t.dept_id = v_dept_id and type = '1';if count_num = 1 thenreturn v_dept_id;elseselect f_company_id(t.parent_id) into company_id from sys_company_dept t where t.dept_id = v_dept_id and rownum < 2;return company_id;end if;end f_company_id;
2.2.2 实现效果
调用上述函数,通过sql来实现想要的效果,如下
sql 如下:with temp1 as(select t.*,f_company_id(t.dept_id) company_idfrom sys_company_dept t)select t1.*,t2.dept_name as company_name from temp1 t1left join sys_company_dept t2 on t1.company_id=t2.dept_idwhere t2.type='1';