SQL round robin: queries SQL statements that support all data of a certain category in an infinitus data table

Source: Internet
Author: User

If you want to query all data of a certain category in a data table that supports infinitus classification

For example, a data table contains a product table that supports infinitus classification.

I want to find the following data and only find the data of "Category A" and all its subcategories.

How can I write SQL statements?

 

The following is my solution

SQL code

-- Create a data table. This can be one of your physical tables.
Declare @ temp table (
ID varchar (20 ),
ParentID varchar (20 ),
Name nvarchar (1, 100 ))

Insert into @ temp values ('A', '', 'category ')
Insert into @ temp values ('B', '', 'category B ')
Insert into @ temp values ('C', '', 'category C ')
Insert into @ temp values ('D', '', 'category D ')
Insert into @ temp values ('a1', 'A', 'classification a1 ')
Insert into @ temp values ('a2 ', 'A', 'classification A2 ')
Insert into @ temp values ('a11', 'a1', 'category a11 ')
Insert into @ temp values ('a12', 'a1', 'category a12 ')

Select * from @ temp

-- Query all data under "Category"
Declare @ $ result table (
ID varchar (20 ),
ParentID varchar (20 ),
Name nvarchar (100 ),
MyLevel int)
Declare @ Level int
Set @ Level = 0
Insert into @ $ result select *, @ Level from @ temp where ID = 'A'

While (@ rowcount> 0)
Begin
Set @ Level = @ Level + 1
Insert into @ $ result
Select a. *, @ level
From @ temp A, @ $ Result B
Where a. parentid = B. ID and mylevel = @ level-1
End
Select * From @ $ result

 

The query result is as follows:

 

The key is to set a flag level for polling to find the desired data.

 

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.