SQL Server unlimited multi-level classification query Solution

Source: Internet
Author: User

In development, users often encounter the problem of unlimited classification. The most common problems are some infinitely level directories. If you are not familiar with SQL Server or are not familiar with the SQL language, this will be a very difficult task. Maybe you can implement similar functions in the end, but it may take a long time and the efficiency is not ideal, the following example may give you some inspiration.

/***** Create a table ****/
Create Table [DBO]. [tree] (
[ID] [int] identity (1, 1) not null,
[Pid] [int] Null,
[Name] [varchar] (10) Collate chinese_prc_ci_as null
) On [primary]

/***** Create a UDF ****/
Create Function DBO. fgettreetable
(
@ ID Int = NULL
)
Returns @ tab table (ID int, PID int, name varchar (10), levint) -- table structure of the returned results
As
Begin
Declare @ levint
Set @ lev= 0

While @ lev= 0 or @ rowcount> 0
Begin
Set @ lev= @ lev+ 1
Insert @ tab (ID, PID, name, column)
Select ID, PID, name, @ levfrom tree where (@ lev= 1 and (pid = @ ID) or (@ ID is null and PID is null ))) or (PID in (select ID from @ tab where lev= @ Lev-1 ))
Order by ID
End
Return
End

You can directly query select * From DBO. fgettreetable (null) to enter all records.

Note: This article is reproduced from: http://drc.cnblogs.com/articles/269062.html. if you have any questions, you can submit them to the original author.

Related Article

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.