刚才在论坛上看到网友一个要求。参考如下,Insus.NET分析一下,可以使用MS SQL Server的递归查询,得到结果。
准备一张表:
根据网友提供的数据,填充此表:
下面语法在SQL Server 2014之下运行正常:
上面代码示例中,完整SQL代码:
WITH TempDeptment ([ID],[PID],[DeptName],[Conjunction]) AS ( SELECT [ID],[PID],[DeptName], CAST([DeptName] AS Nvarchar(1000)) FROM [dbo].[Deptment] WHERE [PID] = 0 UNION ALL SELECT d.[ID], d.[PID], d.[DeptName], CAST(([Conjunction] + N‘/‘ + d.[DeptName]) AS Nvarchar(1000)) FROM TempDeptment AS td,[dbo].[Deptment] AS d WHERE td.[ID] = d.[PID] ) SELECT [ID], [Conjunction] FROM TempDeptment
Insus.NET以前也没有在SQL中实现过递归,现刚好有一个实例,算是练习了。