Sqlserver普通的CTE遞迴示例

2021-06-27 00:20:07 字數 1460 閱讀 1995

--

建立表

declare @t table 

(id int

,pid int

,name varchar

(6))

insert

into @t

select 1,0,'上衣

'union

all

select 2,0,'鞋子

'union

all

select 3,0,'褲子

'union

all

select 4,1,'毛衣

'union

all

select 5,1,'襯衫

'union

all

select 6,2,'球鞋

'union

all

select 7,2,'皮鞋

'union

all

select 8,3,'西褲

'union

all

select 9,3,'筒褲

'union

all

select 10,4,

'羊毛衣

'union

all

select 11,4,

'牛毛衣

'union

all

select 12,5,

'白襯衫

'union

all

select 13,5,

'黑襯衫'

declare @i int

set @i =1 --

引數假定為

;with

depts as(

select

*from @t

where id = 1

union

all

select a.*

from @t a, depts b

where a.pid = b.id)

--取出所有

id為1的子項

select

*from depts/*

id          pid         name

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

1           0           上衣

4           1           毛衣

5           1           襯衫

12          5           

白襯衫

13          5           

黑襯衫

10          4           

羊毛衣

11          4           

牛毛衣

*/

Sqlserver普通的CTE遞迴示例 葉子

建立表 declare t table id int pid int name varchar 6 insert into t select 1,0,上衣 union allselect 2,0,鞋子 union allselect 3,0,褲子 union allselect 4,1,毛衣 uni...

sqlserver的CTE實現遞迴查詢

遞迴查詢 ifobject id digui u is notnull drop table digui create table digui id varchar 50 parentid varchar 50 insert into dbo.digui id,parentid select 第三層...

sql server利用cte遞迴查詢

with cte id,name,parent id as select id,name,parent id from sc district where name 巴中市 union all select sd.id,sd.name,sd.parent id from sc district sd...