SQL Server Query superiors

Source: Internet
Author: User
Tags sql server query

SQL Server does not have a hierarchical search method that is as convenient as in Oracle. I tried to use a stored procedure to implement this function. The stored procedure was previously changed by someone else who wrote something similar.

 

Create proc getparenttype (@ type_id INT)
As
Begin
Declare @ tmp1 table ([ID] int, type_name varchar (100), parent_type_id INT)
Declare @ tmp2 table ([ID] int, type_name varchar (100), parent_type_id INT)
Declare @ tmp3 table ([ID] int, type_name varchar (100), parent_type_id INT)
Insert @ tmp1 select * From td_type where [type_id] = @ type_id
Insert @ tmp2 select * From td_type where [type_id] = @ type_id

While (select count (*) from @ tmp2)> 0
Begin
Insert @ tmp1 select * From td_type where type_id in (select [parent_type_id] From @ tmp2)
Insert @ tmp3 select * From @ tmp2
Delete @ tmp2
Insert @ tmp2 select * From td_type where type_id in (select [parent_type_id] From @ tmp3)
Delete @ tmp3
Insert @ tmp1 select * From td_type where type_id in (select [parent_type_id] From @ tmp2)
End
End
Select distinct (ID), type_name, parent_type_id from @ tmp1
Go

------------------ Run
Exec getparenttype 10015

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.