sqlServer递归查询 with as

sqlServer递归查询 with as

with
district as
(
– 获得第一个结果集,并更新最终结果集
select * from t_tree where node_name= N’辽宁省’
union all
– 下面的select语句首先会根据从上一个查询结果集中获得的id值来查询parent_id
– 字段的值,然后district就会变当前的查询结果集,并继续执行下面的select 语句
– 如果结果集不为null,则与最终的查询结果合并,同时用合并的结果更新最终的查
– 询结果;否则停止执行。最后district的结果集就是最终结果集。
select a.* from t_tree a, district b
where a.parent_id = b.id
)
select * from district

with
district as
(
select * from t_tree where node_name= N’辽宁省’
union all
select a.* from t_tree a, district b
where a.parent_id = b.id
),
district1 as
(
select a.* from district a where a.id in (select parent_id from district)
)
select * from district1

with district as (
select * from t_tree where node_name= N’辽宁省’
union all
select a.* from t_tree a, district b
where a.id = b.id – 故意制造无限循环
)
select * from district
OPTION (MAXRECURSION 5) – 限制特定语句所允许的递归级数,以防止出现无限循环

if exists (
select *
from sys.objects
where name = ‘fn_Test’
and type in (‘FN’ ,‘TF’)
)
drop function dbo.fn_Test;
go

create function dbo.fn_Test
(
@nodename varchar(50)
)
returns @result table (
id int not null
,node_name varchar(50) null
,parent_id int not null
,[description] varchar(255) null
)
as
begin
;with district as (
select *
from t_tree where node_name = @nodename

			 union all

			select a.* 
			from   t_tree a, district b
				   where a.parent_id = b.id
),
district1 as ( 
	select *
	from   district a 
			where a.id in (select parent_id
							from   district)
)

insert into @result
  (
    id
   ,node_name
   ,parent_id
   ,[description]
  )
select id
      ,node_name
      ,parent_id
      ,[description]
from   district1;

return ;

end;
go

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值