Use of SQL Server with recursive queries

Source: Internet
Author: User

1. Data preparation
Suppose there is a table Digui, there are two field IDs int ParentID int
Id ParentID
40
50
70
21st
85
155
97
1411
3015
2315
4118
10423
4230
3930
5339
6739
8839
10739

2. Purpose: By passing in ParentID (=5), all recursive data of the record is returned, i.e.
Id ParentID
85
155
3015
2315
4230
3930
5339
6739
8839
10739

3. SQL Statement Implementation

 with Temp([Id],[ParentID]) as(SelectId, ParentID fromDiguiwhere [ParentID] =  theUnion  AllSelecta.id, A.parentid fromDigui aInner Join Temp  onA.[ParentID] = Temp.[Id])Select *  from Temp
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.