The CTE recursive query in SQL Server 2005 gets a tree

Source: Internet
Author: User
Tags getdate

I feel this CTE recursive query is very good, let me give an example:

[C-sharp]View Plain copy print?
  1. Use city ;
  2. Go
  3. CREATE TABLE Tree
  4. (  
  5. ID int identity (primary) key is not null,
  6. Name varchar () is not null,
  7. Parent varchar () null
  8. )  
  9. Go
  10. Insert Tree VALUES (' university ',null)
  11. Insert Tree VALUES (' College ','University ')
  12. Insert Tree VALUES (' Computer Academy',' College ')
  13. Insert Tree VALUES (' network Engineering ',' Computer Academy ')
  14. Insert Tree VALUES (' information management ',' Computer Academy ')
  15. Insert Tree VALUES (' Telecom Academy',' College ')
  16. Insert Tree VALUES (' academic Office ',' university ')
  17. Insert Tree VALUES (' materials section ',' Dean's Office ')
  18. Insert Tree VALUES (' admissions Office ',' university ')
  19. Go
  20. With CTE as
  21. (  
  22. -->begin A locator point member
  23. Select ID, Name,parent,cast (Name as nvarchar (max)) as te,0 as Levle from Tree where the Parent is null
  24. -->end
  25. Union All
  26. -->begin a recursive member
  27. Select Tree.id, Tree.name,tree.parent,cast (Replicate (", Len (cte.te)) +' |_ ' +tree.name as nvarchar (MAX)) as te,levle+1 as Levle
  28. From Tree INNER join CTE
  29. On tree.parent=cte. Name
  30. -->end
  31. )  
  32. SELECT * from the CTE order by ID
  33. --1. Splitting a CTE expression into an anchor member and a recursive member.
  34. --2. Run an anchor member to create the first call or datum result set (T0).
  35. --3. Run recursive members, use Ti as input (there is only one record here), and ti+1 as output.
  36. --4. Repeat step 3 until the empty set is returned.
  37. --5. Returns the result set.  This is the result of the T0 to Tn execution of UNION all.

The above SQL statement inserts a single piece of data again:

Insert Tree VALUES (' Network 1 class ', ' Network Engineering ')

Running results such as:

Figure 1 Running results

Note: It seems that the field selected at the recursive member must be the data of the tree table, not the one in the CTE result set except the tree, and the fields in the CTE can be referenced here, such as the field Te.

First look at the SQL statement that iterates through the 1th record:

[C-sharp]View Plain copy print?
    1. Select ID, Name,parent,cast (Name as nvarchar (max)) as te,0 as Levle from Tree where the Parent is null

The results obtained are:

Name Parent TE Levle

-------------------------------------

University of NULL University 0

The class SQL statement for the result collection that is obtained recursively for the 2nd time is:

[C-sharp]View Plain copy print?
    1. select tree.id, tree.name,tree.parent,cast (Replicate (   ' , Len (cte.te)) + ' |_ ' +tree.name  as   nvarchar (MAX))   as  te,levle+1  as  levle   
    2. from tree inner join  
    3.     (Select id, name,parent,cast (name  as  nvarchar (max))   as  te,0  as  levle from tree  where parent  is   null )   
    4. as  cte  
    5. on  Tree.parent=cte. name  

The result of the above CTE subquery is the result set of the first recursive query, the SQL run result is:

Similarly, the above three records of the second recursive query are the ' locating members ' of the third query:

"Note here that the above three records are the input of the third recursive, starting with the last one, that is, the first is the record of the Id=9, followed by 7 and 2, and the fourth recursion is similar"

Third recursive collation SQL statement

[C-sharp]View Plain copy print?
    1. Select Tree.id, Tree.name,tree.parent,cast (Replicate (", Len (cte.te)) +' |_ '  +tree.name as nvarchar (MAX)) as te,levle+1 as Levle
    2. From Tree INNER join
    3. (SQL statement for second recursive query) as CTE
    4. On tree.parent=cte. Name

The results are as follows:

In fact, each recursive class of SQL can be shown as follows:

[C-sharp]View Plain copy print?
    1. Select Tree.id, Tree.name,tree.parent,cast (Replicate (", Len (cte.te)) +' |_ '  +tree.name as nvarchar (MAX)) as te,levle+1 as Levle
    2. From Tree INNER join
    3. (The result set of the last recursive query, just the last time, not the previous sum result set)
    4. As CTE
    5. On tree.parent=cte. Name

The fourth time recursion and so on, and the result of the last query is the union of all the recursion above.

Continuation: In the above sq statement query results, the record with ID 10 should be placed after ID 4.

Add two records to the datasheet again:

Insert Tree VALUES (' Accounting section ', ' Computer Academy ')
Insert Tree values (' I ', ' Network 1 classes ')

Modify the above SQL statement again:

[C-sharp]View Plain copy print?
  1. With CTE as
  2. (     
  3. -->begin A locator point member
  4. Select ID, Name,parent,cast (Name as nvarchar (max)) as TE,
  5. row_number () over (order by GETDATE ()) as OrderID
  6. -The most critical is the above field, to get the sort field, sorted by string.
  7. --where the window function must use order BY, but not the integer type, then use the time.
  8. From Tree where the Parent is null
  9. -->end
  10. Union All
  11. -->begin a recursive member
  12. Select Tree.id, Tree.name,tree.parent,cast (Replicate (", Len (cte.te)) +' |_ '+ Tree.name as nvarchar (MAX)) as TE,
  13. CTE. Orderid*100+row_number () over (Order by GETDATE ()) as OrderID
  14. From Tree INNER join CTE
  15. On tree.parent=cte. Name
  16. -->end
  17. )     
  18. SELECT * from CTE
  19. ORDER by LTRIM (OrderID)--to sort this integer data into a string type
  20.   
  21. --Sometimes the integer can be larger than the size, the string is also possible, and the size of the string is a character comparison.
  22. --int + string = = Integer, only string + string = = two string and and
  23. --Recursive query: The second record can refer to the value of the first record
  24. --record identifier of the same level when dynamically loading records: RowNumber () over (order by GETDATE ())
  25. --Extension: You can dynamically get the sub-department under a department. You can also get the department's superior
  26.   
  27. --Summary: First to piece together an integer data, then converted to a string, and finally the order of the string, not the integer data order,

The final result is:

Figure 2 Running results

This way, no matter how many records a user inserts, they can be queried by department and by law.

The CTE recursive query in SQL Server 2005 gets a tree

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.