2016-09-17 15 views
0

Image for SQL Table data如何链接的儿子与他的父亲通过SQL语句

我在SQL Server表我想显示的数据等:

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

哪个RDBMS是这个呢?请添加一个标签来指定您是使用'mysql','postgresql','sql-server','oracle'还是'db2' - 或者其他的东西。 –

+0

你需要自己加入。 –

+0

http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557#285557 –

回答

3

如果S QL服务器(在公布的图像会)

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 
+0

谢谢,工作好你是天才 –