sqlserver的CTE實現遞迴查詢

2022-07-18 06:18:13 字數 1631 閱讀 4961

--

遞迴查詢

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

'第三層

','第一層

'union

select

'第二層

','第一層

'union

select

'第四層

','第一層

'union

select

'第十層

','第二層

'union

select

'第九層

','第二層

'union

select

'第八層

','第五層

'union

select

'第二十層

','第四層

'union

select

'第二十二層

','第四層

'union

select

'第三十層

','第二十層

'union

select

'第三十二層

','第二十層

'union

select

'第四十層

','第三十層

'union

select

'第四十二層

','第三十層

'union

select

'第五十層

','第四十層

'union

select

'第五十二層

','第四十層

'union

select

'第八十層

','第五十層

'union

select

'第八十二層

','第五十層

'union

select

'第一百層

','第九十層

'union

select

'第一百零二層

','第九十層';

with

tempas(

select

id, parentid

from

digui

where

[parentid]=

'第一層

'union

allselect

a.id, a.parentid

from

digui a

inner

join

temp

on a.[

parentid]=

temp.[id]

)select

*from

temp

Sql Server 使用CTE實現遞迴查詢

遞迴cte是sql server 2005中重要的增強之一。一般我們在處理樹,圖和層次結構的問題時需要用到遞迴查詢。cte的語法如下 1with cte as2 3select empid,reportto,fname from employ where empid 1 4union all5 se...

Sqlserver普通的CTE遞迴示例

建立表 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,毛衣 ...

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...