SQL server implements recursive query.

Source: Internet
Author: User

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;

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.