Query for the parent node of the SQL Server tree structure Data child node

Source: Internet
Author: User


Declare @t table (c_id int,pcname varchar (6), ParentID int)
INSERT INTO @t
Select 1, ' Anhui ', 0 union ALL
Select 2, ' Anqing ', 1 UNION ALL
Select 3, ' Anqing ', 2 UNION ALL
Select 4, ' Huaining County ', 2 UNION ALL
Select 5, ' Qianshan County ', 2 UNION ALL
Select 6, ' Susong County ', 2 UNION ALL
Select 7, ' Taihu County ', 2 UNION ALL
Select 8, ' Tongcheng ', 2 UNION ALL
Select 9, ' Wangjiang County ', 2 UNION ALL
Select 10, ' Yuexi County ', 2 UNION ALL
Select 11, ' Congyang County ', 2

; with Maco as
(
SELECT * FROM @t where c_id=11
UNION ALL
Select t.* from @t t,maco m where T.c_id=m.parentid
)
SELECT * from Maco ORDER by c_id

/*
c_id Pcname ParentID
----------- ------ -----------
1 Anhui 0
2 Anqing 1
11 Congyang County 2
*/

Query for the parent node of the SQL Server tree structure Data child node

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.