CTE查询未返回所需结果

时间:2015-02-27 20:43:07

标签: common-table-expression hierarchical-data

我没有在CTE查询中返回下面的第一条记录(稍后显示):

这是我的表:

Key  ParentID  ChildID  (Removed DateJoined Field here)
1       0        1  
3       1       83
4       1       84  
6       83      85  
7       85      86  
8       83      87

我的CTE查询产生以下结果:

ID  Name            Date Joined  Parent ID  Parent Name        Level
83  Hanks, James    2014-09-13      1       Golko, Richard       1
84  Hanks, James    2014-09-13      1       Golko, Richard       1
85  Walker, Jamie   2014-09-13      83      Hanks, James         2
87  Newman, Betty   2014-09-20      83      Hanks, James         2
86  Adams, Ken      2014-09-13      85      Walker, Jamie        3

我如何使用ParentID = 0返回第一条记录?

当我像这样打电话给下面的sproc时:

EXEC UCU_RTG_ProgramStructure_GetMemberTree 0,4

我仍然只得到以parentID = 1开头的结果,如上所示

这是我的CTE查询:

CREATE PROCEDURE [dbo].[UCU_RTG_ProgramStructure_GetMemberTree]
        @ParentID int,
        @MaxLevel int
AS

WITH matrix
AS 
( 
--initialization 
SELECT UserID, DateJoined, ParentID, 1 AS lvl
FROM dbo.UCU_RTG_ProgramStructure
WHERE ParentID = @ParentID
UNION ALL 
--recursive execution 
SELECT p.UserID,p.DateJoined,p.ParentID, lvl+1
FROM dbo.UCU_RTG_ProgramStructure p INNER JOIN matrix m  
ON p.ParentID = m.UserID 
WHERE lvl < @MaxLevel
) 
SELECT matrix.UserID, u.LastName + ', ' + u.FirstName AS Member ,DateJoined,ParentID,u2.LastName + ', ' + u2.FirstName AS Parent,lvl
FROM matrix
INNER JOIN dbo.Users u
ON u.UserID = matrix.UserID
INNER JOIN dbo.Users u2
ON u2.UserID = matrix.ParentID

ORDER BY ParentID

CTE查询很好,除了它不返回parentID = 0记录

...谢谢

1 个答案:

答案 0 :(得分:1)

在查看我的帖子以确定它是正确的之后我终于弄清楚了:最终的select子句是错误的:

SELECT matrix.UserID, u.LastName + ', ' + u.FirstName AS Member ,DateJoined,ParentID,u2.LastName + ', ' + u2.FirstName AS Parent,lvl
FROM matrix
INNER JOIN dbo.Users u
ON u.UserID = matrix.UserID
INNER JOIN dbo.Users u2
ON u2.UserID = matrix.ParentID

最后一个INNER JOIN必须更改为LEFT JOIN,因为没有UserID 0来加入ParentID 0。

希望这可以帮助其他人进行递归CTE查询。