有一个递归的CTE,树路径没有填充

时间:2018-02-22 20:34:51

标签: sql-server common-table-expression

我有以下SQL,它返回正确的层次结构。唯一的问题是它没有填充“treepath”列。对于所有行,该列保持为NULL,但应将所有级别的名称保持为1或更高。

WITH DirectReportsCTE (mgrid, EmpID, ename, mgrname, Lvl, treepath)
AS
(
-- Anchor member definition
    SELECT mgrid, EmpID, ename, mgrname, 0 AS Lvl, CAST(mgrname AS VARCHAR(1024)) AS treepath
    FROM #tmpPeople
    WHERE MgrID IS NULL
    UNION ALL
-- Recursive member definition
    SELECT p.mgrid, p.EmpID, p.ename, p.mgrname, Lvl + 1, 
       CAST(rtrim(d.treepath) + ' -> ' + CAST(p.mgrname AS VARCHAR(1024)) AS VARCHAR(1024)) AS treepath
    FROM #tmpPeople AS p
    inner JOIN DirectReportsCTE AS d
        ON p.MgrID = d.EmpID
)
-- Statement that executes the CTE
insert into #tmpSupers (MgrID, EmpID, ename, mgrname, treepath, Lvl)
(
SELECT MgrID, EmpID, ename, mgrname, treepath, Lvl
FROM DirectReportsCTE dr
)
GO

这些是我正在查询的表格中的字段(#tmpPeople): empid,ename,mgrid,mgrname

我在“树路径”上遗漏了什么并且没有填充?

1 个答案:

答案 0 :(得分:2)

我认为在您的锚点部分mgrname也是NULL(没有经理)。

不完全确定,但我认为你要改变这个

CAST(mgrname AS VARCHAR(1024))

CAST('' AS VARCHAR(1024))

原因:将NULL与字符串值连接最后将为NULL。试试这个:

SELECT 'This' + ' ' + 'works';
SELECT 'This' + NULL + 'not';

HoneyBadger指向CONCAT() function,即使使用NULL也很好用,并且您不需要将所有内容转换为字符串类型:

SELECT CONCAT('This', NULL, ' ', 'works (type tolerant):', 100, '/', GETDATE());

返回(日期格式取决于设置!)

This works (type tolerant):100/Feb 22 2018  9:56PM

但这需要SQL Server 2012 +