我有一个层次表来存储二叉树。我正在使用递归查询来检索基于IntroducerID
“RootID”的树级别。返回的值符合我的预期,但在AgentId
数字增量达到116后,此 CTE 查询不会以分层形式返回 Level 值。
就像它无法再追踪 RootID 一样。
这就是我的表结构的样子;
CREATE TABLE [dbo].[TblHierarchy]
(
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[AgentID] [bigint] NULL,
[AgentName] [varchar](50) NULL,
[RootID] [bigint] NULL,
[IntroducerID] [bigint] NULL,
[Description] [varchar](50) NULL,
[HierarchyTree] [hierarchyid] NULL
) ON [PRIMARY]
以下是表格中的样本数据;
INSERT [dbo].[TblHierarchy] ([ID], [AgentID], [AgentName], [RootID], [IntroducerID], [Description], [HierarchyTree])
VALUES (1, 1, N'Toh', 0, NULL, N'', NULL)
INSERT [dbo].[TblHierarchy] ([ID], [AgentID], [AgentName], [RootID], [IntroducerID], [Description], [HierarchyTree])
VALUES (2, 2, N'Man', 1, 0, N'Child of Toh', NULL)
INSERT [dbo].[TblHierarchy] ([ID], [AgentID], [AgentName], [RootID], [IntroducerID], [Description], [HierarchyTree])
VALUES (3, 3, N'Rul', 1, 0, N'Child of Toh', NULL)
INSERT [dbo].[TblHierarchy] ([ID], [AgentID], [AgentName], [RootID], [IntroducerID], [Description], [HierarchyTree])
VALUES (4, 4, N'Rafiq', 2, 2, N'Child of Man', NULL)
INSERT [dbo].[TblHierarchy] ([ID], [AgentID], [AgentName], [RootID], [IntroducerID], [Description], [HierarchyTree])
VALUES (5, 5, N'Paan', 2, 2, N'Child of Man', NULL)
这是检索信息的查询。
WITH CTE AS
(
SELECT
H1.AgentID,
H1.RootID,
H1.AgentName,
H1.Description [Parent],
Description [Self Description],
CAST(AgentID AS varbinary(MAX)) [Level],
CAST (h1.AgentID AS varchar(max)) [LevelID],
CAST (H1.IntroducerID AS varchar(max)) [IntroducerID]
FROM
TblHierarchy H1
WHERE
H1.RootID = 3
UNION ALL
SELECT
H2.AgentID,
H2.RootID,
H2.AgentName,
c.[Self Description],
Description [Self Description],
c.[Level]+CAST(h2.AgentID AS varbinary(MAX)) AS [Level] ,
c.[LevelID] + '>' + CAST (h2.AgentID AS varchar(max)) [LevelID],
CAST (H2.IntroducerID AS varchar(max)) [IntroducerID]
FROM
TblHierarchy H2
INNER JOIN
CTE c ON h2.RootID = c.AgentID
)
SELECT *
FROM CTE
CROSS APPLY
(SELECT
SUBSTRING(LevelID, 1, CHARINDEX('>', LevelID + '>') - 1) ) c(RootLevelID)
ORDER BY
[Level] DESC
OPTION (MAXRECURSION 0)