用一条sql递归抓取上下级的所有数据并把名称拼接起来

WITH Area2( id,parentid, code, name, parentcode , eLevel,fullname)  AS 
(
    SELECT id,parentid,code, name, parentcode,  0 AS eLevel,CONVERT(varchar(255),name )as fullname
    FROM  Fit_Area
    WHERE  ParentId =0
    UNION ALL
    SELECT e.id,e.ParentId, e.code, e.name, e.parentcode,eLevel + 1 ,CONVERT(varchar(255), (d.fullname+' '+e.Name) ) as  full_name
    FROM Fit_Area e
        INNER JOIN Area2 d
        ON e.ParentId = d.id 
)
SELECT * 
FROM Area2 ;

表字段`

select id,parentid,code, name, parentcode from Fit_area`

数据
用一条sql递归抓取上下级的所有数据并把名称拼接起来_第1张图片
结果
用一条sql递归抓取上下级的所有数据并把名称拼接起来_第2张图片
另外一条的抓取各个省级的所有数据,上面那条也可以用 fullname Like’广东%’

WITH Area2( id,parentid, code, name, parentcode , eLevel,fullname,baseparentid )  AS 
(
    SELECT id,parentid,code, name, parentcode,  0 AS eLevel,CONVERT(varchar(255),name )as fullname,  Id as   baseparentid
    FROM  Fit_Area
    WHERE  ParentId =0
    UNION ALL
    SELECT e.id,e.ParentId, e.code, e.name, e.parentcode,eLevel + 1 ,CONVERT(varchar(255), (d.fullname+' '+e.Name) ) as  full_name,  d.baseparentid  as baseparentid
    FROM Fit_Area e
        INNER JOIN Area2 d
        ON e.ParentId = d.id 
)
SELECT * 
FROM Area2 where   baseparentid=20

你可能感兴趣的:(上下级数据,数据处理,c#,.net,开发语言,sql)