网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

SQLServer通过withas方法查询树型结构

一、with as 公用表表达式

创新互联专注于翁牛特网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供翁牛特营销型网站建设,翁牛特网站制作、翁牛特网页设计、翁牛特网站官网定制、小程序定制开发服务,打造翁牛特网络公司原创品牌,更为您提供翁牛特网站排名全网营销落地服务。

类似VIEW,但是不并没有创建对象,WITH AS 公用表表达式不创建对象,只能被后随的SELECT语句,其作用:

1. 实现递归查询(树形结构)

2. 可以在一个语句中多次引用公用表表达式,使其更加简洁

二、非递归的公共表达式

可以是定义列或自动列和select into 效果差不多

--指定列
with withTmp1 (code,cName)
as
(
 select id,Name from ClassUnis
)
select * from withTmp1
--自动列
with withTmp2 
as
(
 select * from ClassUnis
 where Author = 'system'
)
select * from withTmp2

三、递归的方式

通过UNION ALL 连接部分。通过连接自身whit as 创建的表达式,它的连接条件就是递归的条件。可以从根节点往下查找,从子节点往父节点查找。只需要颠倒一下连接条件。例如代码中条件改为t.ID = c.ParentId即可

with tree as(
 --0 as Level 定义树的层级,从0开始
 select *,0 as Level 
 from ClassUnis
 where ParentId is null
 union all
 --t.Level + 1每递归一次层级递增
 select c.*,t.Level + 1 
 from ClassUnis c,tree t
 where c.ParentId = t.ID
 --from ClassUnis c inner join tree t on c.ParentId = t.ID
)
select * from tree where Author not like'%/%'

SQL Server 通过with as方法查询树型结构

还能通过option(maxrecursion Number) 设置最大递归次数。例如上诉结果Level 最大值为2表示递归两次。我们设置其值为1

with tree as(
 select *,0 as Level from ClassUnis where ParentId is null
 union all
 select c.*,t.Level + 1 from ClassUnis c,tree t where c.ParentId = t.ID
)
select * from tree where Author not like'%/%' 
option(maxrecursion 1)

SQL Server 通过with as方法查询树型结构

好了这篇文章就介绍到这了,希望能帮助到你。


标题名称:SQLServer通过withas方法查询树型结构
标题URL:http://bjjierui.cn/article/iigdho.html

其他资讯