SQLServer 遞迴查詢

2021-07-26 10:49:48 字數 2507 閱讀 8902

感謝文章遞迴查詢,正好趁此機會梳理一下資料庫的遞迴查詢

公用表表示式 (cte) 可以認為是在單個 select、insert、update、delete 或 create view 語句的執行範圍內定義的臨時結果集。公用表表示式可以包括對自身的引用,這種表示式稱為遞迴公用表表示式。

with expression_name [ ( column_name [,...n] ) ]

as( cte_query_definition )

--只有在查詢定義中為所有結果列都提供了不同的名稱時,列名稱列表才是可選的。

--執行 cte 的語句為:

select

from expression_name;

即三個部分:

- 公用表表示式的名字(在with關鍵字之後)

- 查詢的列名(可選)

- 緊跟as之後的select語句(如果as之後有多個對公用表的查詢,則只有第乙個查詢有效)

use dtdl;

with test_cteas(

select tbie.fstablename,tbie.fsid,tbie.fttablename,tbie.ftid,tbie.frouteid from t_bf_instanceentry tbie

where tbie.fttablename = '1'

and tbie.ftid = '1'

union

allselect ctbie.fstablename,ctbie.fsid,ctbie.fttablename,ctbie.ftid,ctbie.frouteid from t_bf_instanceentry ctbie

inner

join test_cte cte on ctbie.fsid=cte.ftid and ctbie.fstablename = cte.fttablename

)select * from test_cte

--限制遞迴次數

option(maxrecursion 10)

with test_cteas(

select tbie.fstablename,tbie.fsid,tbie.fttablename,tbie.ftid,tbie.frouteid,cast(tbie.ftid as nvarchar(4000)) as path

from t_bf_instanceentry tbie

where tbie.fttablename = 't_sal_orderentry'

and tbie.ftid = 121625

union

allselect ctbie.fstablename,ctbie.fsid,ctbie.fttablename,ctbie.ftid,ctbie.frouteid,cte.path+'->'+cast(ctbie.ftid as nvarchar(4000)) path

from t_bf_instanceentry ctbie

inner

join test_cte cte on ctbie.fsid=cte.ftid and ctbie.fstablename = cte.fttablename

)select * from test_cte

--限制遞迴次數

option(maxrecursion 10)

oracle中的遞迴查詢語句為start with…connect by prior,為中序遍歷演算法。

select colname from tablename

start

with 條件1

connect

by 條件2

where 條件3;

select * from t_bf_instanceentry

start

with (ftid=100501

and fttablename = 't_sal_orderentry')

connect

by fsid= prior ftid and fstablename =prior fttablename

select tbie.*, substr(sys_connect_by_path(ftid,'->'),3)  name_path from t_bf_instanceentry tbie

start

with (ftid=100501

and fttablename = 't_sal_orderentry')

connect

by fsid= prior ftid and fstablename =prior fttablename

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

sqlserver 遞迴查詢

構建遞迴結構的表 資料是虛構的 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...