SQL Server根據子節點查詢所有父節點的代碼示例
作者:LyDevin
本文我們主要介紹了SQL Server根據子節點查詢所有父節點的代碼示例,初學者可以套用其格式即可完成子節點查詢所有父節點的功能,希望能夠對您有所幫助。
SQL Server數據庫根據子節點查詢所有父節點的方法是本文我們主要要介紹的內容,接下來我們就通過一個代碼示例來介紹這一過程的實現。
- create table tb(id varchar(3) , pid varchar(3) , name varchar(10))
- insert into tb values('001' , null , '廣東省')
- insert into tb values('002' , '001' , '廣州市')
- insert into tb values('003' , '001' , '深圳市')
- insert into tb values('004' , '002' , '天河區')
- insert into tb values('005' , '003' , '羅湖區')
- insert into tb values('006' , '003' , '福田區')
- insert into tb values('007' , '003' , '寶安區')
- insert into tb values('008' , '007' , '西鄉鎮')
- insert into tb values('009' , '007' , '龍華鎮')
- insert into tb values('010' , '007' , '松崗鎮')
- go
- --查詢指定節點及其所有父節點的函數
- create function f_pid(@id varchar(3)) returns @t_level table(id varchar(3))
- as
- begin
- insert into @t_level select @id
- select @id = pid from tb where id = @id and pid is not null
- while @@ROWCOUNT > 0
- begin
- insert into @t_level select @id select @id = pid from tb where id = @id and pid is not null
- end
- return
- end
- go
- --調用函數查詢002(廣州市)及其所有父節點
- select a.* from tb a , f_pid('002') b where a.id = b.id order by a.id
- /*
- id pid name
- ---- ---- ----------
- 001 NULL 廣東省
- 002 001 廣州市
以上的代碼就就實現了SQL Server根據子節點查詢所有父節點的功能,本文就介紹到這里了,希望本次的介紹能夠對您有所收獲!
【編輯推薦】
責任編輯:趙鵬
來源:
博客園