mssql查询所有上下级
if exists (select * from sys.all_objects where name='GetOrgTreeByID')
begin
drop proc GetOrgTreeByID
end
go
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:
-- Description: <获取组织架构所有上下级>
-- =============================================
CREATE PROCEDURE [dbo].[GetOrgTreeByID]
@ID int,--查询的ID
@QueryType nvarchar(50) --查询方式,down:查询所有下级,up:查询所有上级
AS
BEGIN
IF(@QueryType='down')
begin
with DownLevel as
(
select id,ParentID,OrgName, 0 as lvl from tabOrg
where id = @ID
union all
select d.id,d.ParentID,d.Orgname,lvl + 1 from DownLevel c inner join tabOrg d
on c.Id = d.ParentID
)
select * from DownLevel
end
else
begin
with UpLevel as
(
select id,ParentID,OrgName, 0 as lvl from tabOrg
where id = @ID
union all
select d.id,d.ParentID,d.Orgname,lvl + 1 from UpLevel c inner join tabOrg d
on c.ParentID = d.id
)
select * from UpLevel
end
END
GO
--exec GetOrgTreeByID 2,'up'
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步