Method of querying a tree structure using SQL Server 2005/2008 recursive CTE _mssql2005

Source: Internet
Author: User
Tags fam
Here is a simple example of a family tree:
Copy Code code as follows:

DECLARE @TT TABLE (ID int,relation varchar (), Name varchar (), ParentID int)
INSERT @TT SELECT 1, ' great grandfather ', ' Thomas Bishop ', null UNION all
SELECT 2, ' Grand Mom ', ' Elian Thomas Wilson ', and 1 UNION all
SELECT 3, ' Dad ', ' James Wilson ', 2 UNION all
SELECT 4, ' Uncle ', ' Michael Wilson ', 2 UNION all
SELECT 5, ' Aunt ', ' Nancy Manor ', 2 UNION all
SELECT 6, ' Grand Uncle ', ' Michael Bishop ', 1 UNION all
SELECT 7, ' Brother ', ' David James Wilson ', 3 UNION all
SELECT 8, ' Sister ', ' Michelle Clark ', 3 UNION all
SELECT 9, ' Brother ', ' Robert James Wilson ', 3 UNION all
SELECT, ' Me ', ' Steve James Wilson ', 3

----------Query---------------------------------------
; With Familytree
As (
SELECT *, CAST (NULL as VARCHAR ()) as ParentName, 0 as Generation from @TT
WHERE ParentID is NULL
UNION All
SELECT Fam.*,familytree.name as ParentName, Generation + 1 from @TT as Fam
INNER JOIN familytree on fam.parentid = familytree.id
) SELECT * from Familytree

Output:


Hope to help you

Author:petter Liu

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.