SQL does not use recursion, but uses a flat history for the region level.

Source: Internet
Author: User

Region table structure

Id parentid name

1 0 A1

2 1 A1-1

......

/* Temporary table */

Create Table # t_dq (
Id integer null,
Parentid integer null,
Name varchar (50) null,
Grade integer null,/* level */
State varchar (10) null/* 1: not processed; 2: processed */
)

/* SQL indicates the query region, including the sub-region */

Insert into # t_dq (ID, parentid, name, grade, state)
Select ID, parentid, name, 1, '1' from t_dq where parentid = @ area/* region to be queried */

/* Insert sub-regions cyclically */
Select @ ID = min (ID) from # t_dq
While @ ID is not null
Begin
Select @ grade = Grade from # t_dq where id = @ ID
Insert into # t_dq (ID, parentid, name, grade, state)
Select ID, parentid, name, @ grade + 1, '1' from # t_dq1 where parentid = @ ID
Update # t_dq set state = '2' where id = @ ID
Select @ ID = min (ID) from # t_dq where State <> '2'
End

 

Select * from # t_dq

 

Hope to help you!

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.