SQL Server recursive query

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 ...

[SQL]View Plaincopyprint?
  1. If object_id (' TB ',' N ') is not null
  2. drop table TB;
  3. Create table TB (ID varchar (3), PID varchar (3), name varchar (10));
  4. INSERT INTO TB values (' 001 ', null, ' Guangdong province ');
  5. INSERT INTO TB values (' 002 ', ' 001 ', ' Guangzhou ');
  6. INSERT INTO TB values (' 003 ', ' 001 ', ' Shenzhen ');
  7. INSERT INTO TB values (' 004 ', ' 002 ', ' Tianhe District ');
  8. INSERT INTO TB values (' 005 ', ' 003 ', ' Luohu ');
  9. INSERT INTO TB values (' 006 ', ' 003 ', ' Futian District ');
  10. INSERT INTO TB values (' 007 ', ' 003 ', ' bao ' an ');
  11. INSERT INTO TB values (' 008 ', ' 007 ', ' West Township ');
  12. INSERT INTO TB values (' 009 ', ' 007 ', ' Longhua Town ');
  13. INSERT INTO TB values (' 010 ', ' 007 ', ' Songgang ');
  14. SELECT * from TB;
  15. With CTE as
  16. (
  17. Select A.id,a.name,a.pid from TB a where id=' 003 '
  18. Union All
  19. Select K.id,k.name,k.pid from TB K inner join CTE C on c.id = k.pid
  20. )SELECT * from CTE


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

Transferred from: http://blog.csdn.net/myxx520/article/details/6922682

SQL Server recursive query (GO)

Related Article

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.