如何通过sql语句链接儿子与他的父亲

时间:2016-09-17 18:00:13

标签: sql sql-server tsql

Image for SQL Table data

我在SQL服务器中有表,我希望显示如下数据:

  1. 史密斯
  2. Johnson Smith
  3. 威廉姆斯史密斯
  4. 布朗约翰逊史密斯

1 个答案:

答案 0 :(得分:3)

IF SQL Server(按发布的图片进行)

Declare @Table table (ID int,CLevel int,CParent int ,Name varchar(50))
Insert into @Table values 
(1,1,NULL,'Smith'),
(2,2,1    ,'Johnson'),
(3,2,1    ,'Williams'),
(7,3,2    ,'Brown')


;with cteHB (ID,CParent,Lvl,Name,PathName) as (
    Select  ID
           ,CParent
           ,Lvl=1
           ,Name
           ,PathName = cast(Name as varchar(500)) 
     From   @Table 
     Where  CParent is null
     Union  All
     Select cteCD.ID
           ,cteCD.CParent,cteHB.Lvl+1
           ,cteCD.Name 
           ,PathName = cast(concat(cteCD.Name,' ',cteHB.PathName) as varchar(500))
     From   @Table cteCD 
     Join   cteHB on cteCD.CParent = cteHB.ID)
Select A.ID
      ,A.CParent
      ,A.Lvl
      ,A.Name
      ,A.PathName
 From cteHB A

返回

ID  CParent  Lvl  Name       PathName
1   NULL     1    Smith      Smith
2   1        2    Johnson    Johnson Smith
3   1        2    Williams   Williams Smith
7   2        3    Brown      Brown Johnson Smith