Have the following data sheet
If we want to query all the child nodes of the data with ID 003 We can use the CTE recursive query to complete ...
if object_id('TB','N') is not NULL Drop TableTB;Create TableTB (IDvarchar(3), PIDvarchar(3), namevarchar(Ten));Insert intoTbValues('001',NULL,'Guangdong province');Insert intoTbValues('002','001','Guangzhou'); Insert intoTbValues('003','001','Shenzhen') ;Insert intoTbValues('004','002','Tianhe District') ;Insert intoTbValues('005','003','Luohu District');Insert intoTbValues('006','003','Futian District') ;Insert intoTbValues('007','003','Baoan District') ;Insert intoTbValues('008','007','West Township') ;Insert intoTbValues('009','007','Longhua Town');Insert intoTbValues('010','007','Songgang Town');Select * fromTB; withCte as ( SelectA.id,a.name,a.pid fromTB AwhereId='003' Union All SelectK.id,k.name,k.pid fromTB KInner JoinCTE C onC.id=k.pid)Select * fromCTE
The query results are as follows:
003 Shenzhen City 001
005 Luohu District 003
006 Futian District 003
007 Baoan District 003
008 West Township 007
009 Longhua Town 007
010 Songgang Town 007
SQL SERVER makes recursive queries