好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

SQLServer公用表表达式(CTE)实现递归的方法

公用表表达式简介:

公用表表达式 (CTE) 可以认为是在单个 SELECT、INSERT、UPDATE、DELETE 或 CREATE VIEW 语句的执行范围内定义的临时结果集。CTE 与派生表类似,具体表现在不存储为对象,并且只在查询期间有效。与派生表的不同之处在于,公用表表达式 (CTE) 具有一个重要的优点,那就是能够引用其自身,从而创建递归 CTE。递归 CTE 是一个重复执行初始 CTE 以返回数据子集直到获取完整结果集的公用表表达式。

下面先创建一个表,并插入一些数据:

create table Role_CTE
(
 Id  int    not null,
 Name nvarchar(32) not null,
 ParentId int  not null 
)
insert into Role_CTE(Id,Name,ParentId)
select '1','超级管理员','0' union 
select '2','管理员A','1' union 
select '3','管理员B','2' union 
select '4','会员AA','2' union 
select '5','会员AB','2' union 
select '6','会员BA','3' union 
select '7','会员BB','3' union 
select '8','用户AAA','4' union 
select '9','用户BBA','7' 
-- 创建一个复合聚集索引
create clustered index Clu_Role_CTE_Index
on Role_CTE(Id,ParentId)
with
(
 pad_index=on,
 fillfactor=50,
 drop_existing=off,
 statistics_norecompute=on
)
select * from Role_CTE 

查看更多关于SQLServer公用表表达式(CTE)实现递归的方法的详细内容...

  阅读:47次