SQL processing Multilevel classification, query results are tree-shaped structure _mssql

Source: Internet
Author: User
The disadvantage of this treatment is: if the amount of data, a lot of subcategories, up to 4 level, this method to handle extreme occupancy database connection pool
has a significant impact on performance.

If you use a CTE with the following SQL, you can query the results in a single pass, and the performance is good.
The performance of the temporary table is better and more convenient than the program processing (the data is very large)
Copy Code code as follows:

With the area as (
Select *,id px,cast (id as nvarchar (4000)) px2 from region where parentid=0
UNION ALL
Select A.*,b.px,b.px2+ltrim (a.region_id) from region A join area B on a.parentid=b.id
) select * from area ORDER by px,px2


Can query the results--all categories and corresponding categories
ID Title ParentID
1 Guangdong Province 0
2 Guangzhou 1
3 Baiyun District 2
4 Shenzhen 1
5 Hunan Province 0
6 Changsha 5
7 Zhuzhou 5
Copy Code code as follows:

With the area as (
SELECT * from region where parentid=1
UNION ALL
Select A.* from region A join area B on a.parentid=b.id
) SELECT * FROM area

Can query the results--Specify the classification and the corresponding classification
ID Title ParentID
1 Guangdong Province 0
2 Guangzhou 1
3 Baiyun District 2


Performance Analysis:
For a 3,500-region record data sheet, which has a province, city, county level 3
The query takes 1 seconds, visually it feels a little bit slower, but it doesn't affect
A small amount of data, using absolutely no pressure

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.