SQL server implements recursive query.
This example describes how SQL server implements recursive queries. We will share this with you for your reference. The details are as follows:
Sometimes recursive queries are required for tree-structured data. After searching for the data on the Internet and referring to the articles of great gods, we found it quite simple to use it as a small note for future use.
SQL server supports recursive query through CTE, which is useful for querying data in a tree or hierarchy.
The general tree table structure is as follows. I believe everyone is familiar with it.
Id |
Title |
Pid |
1 |
Level 1 Node |
0 |
2 |
Level 2 node |
1 |
3 |
Level 3 Node |
2 |
4 |
Level 4 node |
3 |
5 |
Level 5 Node |
4 |
The code below
---------- SQL server recursive query ------------ query all upper-level nodes with uCte as (select. id,. title,. pid from tree_table a where id = 3 -- current node union all select k. id, k. title, k. pid from tree_table k inner join uCte c on c. pid = k. id) select * from uCte; -- Query all upper-level nodes with dCte as (select. id,. title,. pid from tree_table a where id = 3 -- current node union all select k. id, k. title, k. pid from tree_table k inner join dCte c on c. id = k. pid) select * from dCte;