SQL SERVER makes recursive queries

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.