SQL2005實現表記錄遞迴查詢

2021-05-23 06:35:50 字數 673 閱讀 9955

if not object_id('tb') is null

drop table tb

gocreate table tb([id] int,[parid] int)

insert tb

select 1,0 union all

select 2,0 union all

select 3,0 union all

select 4,1 union all

select 5,4 union all

select 6,3 union all

select 7,6 union all

select 8,4 union all

select 9,1 union all

select 10,9

go--select * from tb

-->sql查詢如下:

with t as

(select *,id grp1,cast(id as nvarchar(max)) grp2 from tb where parid=0

union all

select tb.*,t.grp1,t.grp2+ltrim(tb.id) from tb,t where tb.parid=t.id

)select * from t order by grp1,grp2

查sql表記錄數

create table data name varchar 100 row varchar 100 reserved varchar 100 data varchar 100 index size varchar 100 unused varchar 100 declare name varcha...

SQL2005遞迴查詢語法

create table code catalog structure catalogid nvarchar 10 col varchar 10 parentid nvarchar 10 insert into code catalog structure select 我是一層的一 aaa roo...

sql2005 的樹形遞迴查詢

在sqlserver中從2005開始支援樹形遞迴查詢,其方法如下 從給定的根節點 可以是多個 向下查詢,直到所有子節點 with myt2 as select from 表名 where 根節點查詢條件 union all select 表名.from myt2 inner join 表名 on m...