ifobject_id('UF_GetChildDept','tf') isnotnull dropfunction UF_GetChildDept go -- ============================================= -- Author: <Author,,Name> adandelion -- Create date: <Create Date,,>2007-12-03 -- Description: <Description,,> 根据传入的部门ID,返回它下面的所有子部门。 -- ============================================= createfunction UF_GetChildDept( @DeptIdint ) returns@tbtable (id int) as begin insertinto@tb select dept_id from dept where parentdept_id =@deptid while@@Rowcount>0--只要有下级节点就循环 begin insertinto@tb select dept_id --取出刚刚插入的deptid,去部门表里找parentdept_id = deptid的记录。 from dept as a innerjoin@tbas b on a.parentdept_id = b.id and a.dept_id notin(select id from@tb) end return end go select* from dbo.UF_GetChildDept(7)
三、根据部门IP获得它的上级部门
ifobject_id('UF_GetParentDept','tf') isnotnull dropfunction UF_GetParentDept go -- ============================================= -- Author: <Author,,Name> adandelion -- Create date: <Create Date,,>2007-12-03 -- Description: <Description,,> 根据传入的部门ID,返回它的上级部门。 -- ============================================= createfunction UF_GetParentDept( @DeptIdint ) returns@tbtable (id int) as begin insertinto@tb select parentdept_id from dept where dept_id =@deptid while@@Rowcount>0-- begin insertinto@tb select parentdept_id -- from dept as a innerjoin@tbas b on a.dept_id = b.id and a.parentdept_id notin(select id from@tb) end return end go select* from dbo.UF_GetParentDept(7)