【发布时间】:2017-08-31 12:26:35
【问题描述】:
我已经盯着这段代码太久了,试图弄清楚为什么我的最终查询返回了意外的结果。
任何帮助将不胜感激。提前致谢。
给定以下代码(在 SQL Server 2008 R2 上运行):
使用临时数据库; 声明@emp--loyee 桌子 ( EmployeeID int 非空 ,EmployeeName nvarchar(50) NOT NULL 主键(员工 ID) ) 插入@emp 选择 1,“弗雷德” 联盟 选择 2,“玛丽” 联盟 选择 3,“乔” 联盟 选择 4,'比尔' 声明 @grp 表 ( GroupID int 非空 ,组名 nvarchar(50) 主键(组 ID) ) 插入@grp 选择 1,'组 1' 联盟 选择 2,'组 2' 联盟 选择 3,'组 3' 声明@empgrp 表( EmployeeID int 非空 ,GroupID int NOT NULL 主键(员工 ID、组 ID) ) 插入@empgrp 选择 1,1 联盟 选择 2,1 联盟 选择 3,1 联盟 选择 4,2 声明@grpgrp 表( GroupID int 非空 ,ParentGroupID int ,唯一的集群(GroupID,ParentGroupID) ) 插入@grpgrp 选择 1,2 联盟 选择 2,3; WITH AllEmpGroups (EmployeeID,GroupID,RootGroupID) 作为 ( SELECT CAST(NULL as int) as EmployeeID,pgrp.GroupID,pgrp.ParentGroupID 从@grpgrp pgrp 左加入@grpgrp ggrp ON pgrp.ParentGroupID = ggrp.GroupID 联合所有 SELECT e.EmployeeID,eg.GroupID,aeg.RootGroupID 从@emp e 加入@empgrp 例如 ON e.EmployeeID = eg.EmployeeID 加入@grpgrp ggrp ON eg.GroupID = ggrp.GroupID 加入 AllEmpGroups aeg ON aeg.GroupID = ggrp.ParentGroupID ) 选择员工 ID、组 ID、根组 ID 来自 AllEmpGroups我得到的是:
+------------+---------+-------------+ |员工ID |组ID |根组ID | +------------+---------+-------------+ |空 | 1 | 2 | |空 | 2 | 3 | | 1 | 1 | 3 | | 2 | 1 | 3 | | 3 | 1 | 3 | +------------+---------+-------------+我期望/想要得到的是:
+------------+---------+-------------+ |员工ID |组ID |根组ID | +------------+---------+-------------+ |空 | 1 | 2 | |空 | 2 | 3 | | 4 | 2 | 3 | | 1 | 1 | 3 | | 2 | 1 | 3 | | 3 | 1 | 3 | +------------+---------+-------------+底线,我想要给定根组下所有员工的完整递归堆栈,每行都有根组 ID。
我错过了什么?
【问题讨论】:
-
如何使用
hierarchyid数据类型。 -
以
SQL Server 2008docs.microsoft.com/en-us/sql/t-sql/data-types/…开头
标签: sql sql-server tsql recursion recursive-query