SQL Server 根据树状结构表生成以/号分割的路由字符串
很多情况下,我们有必要把树形结构进行数据梳理。比如,要方便的过滤出一个父节点下的所有子节点等等。。。
这个时候,我们可以生成一个路径表字符串,在应用时只需要对该字符串进行索引即可达成目的。
目标:按图示的部门结构树,获取本身的完整路径字符串。比如,前道工序部门,其部门代码为PDTE,上级部门为PD生产部,按结构树获取到一个/PD/PDTE/的字符串。
先来一个简单点的展示:
WITH T AS (SELECT CAST('/' + DeptCode + '/' AS NVARCHAR(MAX)) AS DpPath, DeptRKEY AS DpKey FROM Base_Department WHERE (ILevel = 1)--指定父级起点 UNION ALL SELECT CAST(t.DpPath + D.DeptCode + '/' AS NVARCHAR(MAX)) AS DpPath, D.DeptRKEY AS DpKey FROM Base_Department AS D INNER JOIN T ON D.ParentRKEY = T.DpKey)--设置递归关联 SELECT DpPath, DpKey FROM T--输出结果
输出如下图:
然后开个稍微复杂点的,带上级机构关联上:
WITH T AS (SELECT '/' + CAST(DeptCode AS NVARCHAR(MAX)) + '/' AS DpPath, DeptRKEY AS DpKey, DeptNameLL AS DpNameLL, DeptNameLI AS DpNameLI, ILevel AS DpLevel, ISEQ AS DpSEQ, BranchRKEY FROM Base_Department WHERE (ILevel = 1) UNION ALL SELECT CAST(t.DpPath + D.DeptCode + '/' AS NVARCHAR(MAX)) AS DpPath, D.DeptRKEY AS DpKey, D.DeptNameLL AS DpNameLL, D.DeptNameLI AS DpNameLI, D.ILevel AS DpLevel, D.ISEQ AS DpSEQ, D.BranchRKEY FROM Base_Department AS D INNER JOIN T ON D.ParentRKEY = T.DpKey) SELECT '/' + BranchCode + '/' AS DpPath, BranchCode AS DpKey, BranchNameLL AS DpNameLL, BranchNameLI AS DpNameLI, 0 AS DpLevel, 0 AS DpSEQ FROM Base_Branch UNION ALL SELECT '/' + B.BranchCode + T.DpPath AS Expr1, STR(T.DpKey) AS DpKey, T.DpNameLL, T.DpNameLI, T.DpLevel, T.DpSEQ FROM T INNER JOIN Base_Branch AS B ON T.BranchRKEY = B.BranchRKEY
输出如下:
如果,某些场合下,就能很好的利用这个DpPath了。