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'

转载于:https://www.cnblogs.com/SilenceTom/p/5576050.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值