sqlserver 递归查询:向上向下

sqlserver 递归查询:向上向下


--由父项递归下级 
with cte(id,parentid,text) 
as 
(--父项 
select id,parentid,text from treeview where parentid = 450 
union all 
--递归结果集中的下级 
select t.id,t.parentid,t.text from treeview as t 
inner join cte as c on t.parentid = c.id 

select id,parentid,text from cte 


--------------------- 


--由子级递归父项 
with cte(id,parentid,text) 
as 
(--下级父项 
select id,parentid,text from treeview where id = 450 
union all 
--递归结果集中的父项 
select t.id,t.parentid,t.text from treeview as t 
inner join cte as c on t.id = c.parentid 

select id,parentid,text from cte


-----------------------------

eg:

写个带返回值的存储过程调用一下,比较快:

create proc getOrgId(
    @GroupID int,--输入参数
    @id int output --输出参数
)
as    
   with cte([GroupID],[G_ParentID],[G_Level])
as
(
select [GroupID],[G_ParentID],[G_Level] from [sys_Group] where [GroupID] =@GroupID
union all
select t.[GroupID],t.[G_ParentID],t.[G_Level] from [sys_Group] as t
inner join cte as c on t.[GroupID] = c.[G_ParentID]
)
select @id=[GroupID] from cte  where cte.[G_Level]='2'

--执行这个带返回值的存储过程
declare @orgid int --声明一个变量用来接收执行存储过程后的返回值
exec getOrgId '1734',@orgid output
select @orgid as orgid;--as是给返回的列值起一个名字


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值