Sqlserver: CTE function processing recursion (with syntax)

Source: Internet
Author: User

When we do classification, we always encounter recursive processing. For example, the region is an example. China -- Beijing -- Xicheng district, we can store such information in a data table, use parentid to distinguish between the root node and the leaf node. If we want to do navigation, we get "Xicheng district", but we need to get his parent level or husband level, one way is to useProgramIs also very simple, another way is to use the database function. Since the database can do this, why the program?

This can also be handled in versions earlier than sqlserver2005, but stored procedures were used at the time,CodeThere are also many tables. During table design, a field indicating "depth" is added. At that time, I also wrote relatedArticle, See:

Unlimited storage process classification (1)

Unlimited classification of stored procedures (2)

Unlimited storage process classification (3)

However, when learning the new features of sqlserver2005, I noticed that the with statement can implement this function, and the code is simple, concise, and the most important thing is a good understanding.

The following is a recursive table structure:

The parentid records the relationship between them;

For example, what if we want to query data with ID = 10008 and parentid is 10008? For example:

Well, there's no suspense. Go directly to the code! In fact, it is easy to understand:

With categoryinfo (

Select ID, text, parentid from recursive where id = 10008

Union all

Select a. ID, A. Text, A. parentid from recursive as A, categoryinfo as B where a. parentid = B. ID

)

Select * From categoryinfo

 

Check whether it is simple, concise, and easy to understand!

Try it now!

This is a top-down query. If it is a bottom-up query, how can it be checked? Let's just put it apart!

 

Tag: sqlserver, with statement, with, recursion, infinite Recursion

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.