樹形資料查詢示例

2021-04-01 15:22:00 字數 1224 閱讀 1921

--參考

--樹形資料查詢示例

--示例資料

create table [tb]([id] int identity(1,1),[pid] int,name varchar(20))

insert [tb] select 0,'中國'

union  all  select 0,'美國'

union  all  select 0,'加拿大'

union  all  select 1,'北京'

union  all  select 1,'上海'

union  all  select 1,'江蘇'

union  all  select 6,'蘇州'

union  all  select 7,'常熟'

union  all  select 6,'南京'

union  all  select 6,'無錫'

union  all  select 2,'紐約'

union  all  select 2,'舊金山'

go--查詢指定id的所有子

create function f_cid(

@id int

)returns @re table([id] int,[level] int)

asbegin

declare @l int

set @l=0

insert @re select @id,@l

while @@rowcount>0

begin

set @l=@l+1

insert @re select a.[id],@l

from [tb] a,@re b

where a.[pid]=b.[id] and b.[level]=@l-1

end/*--如果只顯示最明細的子(下面沒有子),則加上這個刪除

delete a from @re a

where exists(

select 1 from [tb] where [pid]=a.[id])

--*/

return

endgo

--呼叫(查詢所有的子)

select a.*,層次=b.[level] from [tb] a,f_cid(2)b where a.[id]=b.[id]

go--刪除測試

drop table [tb]

drop function f_cid

go

樹形資料結構的級聯查詢(子查詢 遞迴)

說明 當一張表中同時存在id和pid parent id 我們需要用子連線查出其中的級聯關係,並將資料展示為多級列表 樹形資料結構 參考以下查詢的方法。查詢課程型別的樹形結構,多級選單資料 return treedata public ajaxresult gettreedata override ...