sqlserver:cte function processing recursion (with syntax)

Source: Internet
Author: User

When we do classification processing, we always encounter recursive processing, such as the region is an example, China-Beijing-Xicheng District, we can store such information in a data table, using ParentID to distinguish between root node and leaf node. If we want to do navigation, get "Xicheng", but also to get his father, or father, one way is to use the program to deal with, is very simple, another way is to use the function of the database. Since the database can complete this matter, why use the program?

In previous versions of SqlServer2005, it was also possible to handle this situation, but at the time the stored procedure was used, the code was more, the table was designed, and a field representing "depth" was added, and I wrote the relevant article, see:

Unlimited class classification for stored procedures (1)

Unlimited class classification for stored procedures (2)

Unlimited class classification for stored procedures (3)

However, when learning the new features of SqlServer2005, it is important to note that the WITH statement can achieve such a function, and that the code is simple, concise, and, above all, a good understanding.

The following is a recursive table structure diagram:

The ParentID in the inside records the relationship between them;

For example, we want to query the ID = 10008, and ParentID 10008 of the data to do? Such as:

Oh, do not leave suspense, directly on the code bar! It's pretty easy to understand:

With CategoryInfo as (  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

See if it is simple, concise, good understanding!

Give it a try!

This is from the top down, if you look from the bottom up, how to check it, you extrapolate it!

sqlserver:cte function processing recursion (with syntax)

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.