sqlserver 遞迴查詢

2022-02-02 13:22:33 字數 1137 閱讀 9093

-- 構建遞迴結構的表(資料是虛構的)

drop table t;

create table t

(id int, name varchar(6), pid int

);insert into t

select 1,'安徽',0 union all

select 2,'安慶',1 union all

select 3,'安慶市',2 union all

select 4,'懷寧縣',2 union all

select 5,'潛山縣',2 union all

select 6,'宿松縣',2 union all

select 7,'太湖縣',3 union all

select 8,'桐城市',3 union all

select 9,'望江縣',4 union all

select 10,'岳西縣',4 union all

select 11,'樅陽縣',2

;-- 遞迴查詢某個節點的所有父節點

;with cte as

(select * from t where id=11

union all

select t.* from t,cte where t.id=cte.pid

)select * from cte order by id;

-- 遞迴查詢整個樹

但是,這個結果排序是有問題的,如太湖縣應該掛在安慶縣下面。如果解決這個問題?請不啻指教

SQLServer 遞迴查詢

感謝文章遞迴查詢,正好趁此機會梳理一下資料庫的遞迴查詢 公用表表示式 cte 可以認為是在單個 select insert update delete 或 create view 語句的執行範圍內定義的臨時結果集。公用表表示式可以包括對自身的引用,這種表示式稱為遞迴公用表表示式。with expre...

sqlserver 遞迴查詢

有如下資料表 假如我們要查詢id為003的資料的所有子節點我們可以使用cte 遞迴查詢完成.sql view plain copy print?if object id tb n is notnull drop table tb create table tb id varchar 3 pid va...

sql server遞迴查詢

1 既然要談到sql,資料庫表是必須的 2 資料結構 3 獲取某個節點的所有子節點 傳統的寫法 sql2000 很麻煩,暫且就不寫了 來看看cte的寫法 create proc sp gettreebyid treeid int asbegin with ctetree as select from...