使用HierarchyID在SQL Server中选择Parent和Child

时间:2014-09-05 01:35:01

标签: sql-server

我有HierarchyID的表,想要在子属性上选择父子项。

这是表格:

CREATE TABLE #BOMTbl
(
  ItemNo   HIERARCHYID NOT NULL,
  Lvl AS ItemNo.GetLevel() PERSISTED,
  MatID VARCHAR(25) NULL,
  CONSTRAINT PK_#BOMTbl PRIMARY KEY NONCLUSTERED(ItemNo)
);

insert into #BOMTbl (ItemNo,MatID) values
('/1/',''),
('/1/1/',''),
('/1/1/1/','MA-A'),
('/1/1/2/','MA-A'),
('/1/1/3/','MA-B'),
('/1/2/',''),
('/1/2/1/','MA-B'),
('/1/2/2/','MA-B'),
('/1/3/',''),
('/1/3/1/','PW-A'),
('/1/3/2/','PW-A'),
('/1/4/',''),
('/1/4/1/','PW-B'),
('/1/4/2/','PW-B'),
('/1/5/','0001'),
('/1/6/','0001'),
('/1/7/','0002'),
('/1/8/','0003')

我想选择具有如下结果的表:

ItemNo  ItemID  Lvl MatID
0x5AC0  /1/1/   2   
0x5AD6  /1/1/1/ 3   MA-A
0x5ADA  /1/1/2/ 3   MA-A
0x5B40  /1/2/   2   
0x5ADE  /1/1/3/ 3   MA-B
0x5B56  /1/2/1/ 3   MA-B
0x5B5A  /1/2/2/ 3   MA-B 

3 个答案:

答案 0 :(得分:0)

以下查询会有帮助吗?

select ItemNo, ItemNo.ToString() AS ItemID, Lvl, MatID from #BOMTbl
WHERE ItemNo.IsDescendantOf('/1/1/') = 1
UNION
select ItemNo, ItemNo.ToString() AS ItemID, Lvl, MatID from #BOMTbl
WHERE ItemNo.IsDescendantOf('/1/2/') = 1

答案 1 :(得分:0)

select ItemNo, ItemNo.ToString() AS ItemID, Lvl, MatID from BOMTbl p
WHERE exists
(select * from BOMTbl c
 where c.MatID like 'MA%'
 and (c.ItemNo.GetAncestor(1) = p.ItemNo 
      or c.ItemNo.GetAncestor(0) = p.ItemNo ) )

SQLFiddle

答案 2 :(得分:0)

我想出了:

with cte as (
    select *
    from #BOMTbl
    where MatId like 'MA%'
)
select *
from cte as child
union
select parent.* 
from cte as child
join #BOMTbl as parent
    on child.ItemNo.GetAncestor(1) = parent.ItemNo