您可以使用下面的方法。我写了一个表值函数,“GetChild”。它递归地遍历记录以获取所有依赖关系,最后获得所有这些依赖关系的RefId。
Create table hierarchy (Id int, RefId varchar(10), FromRefId varchar(10))
GO
insert into hierarchy
select 1,'RH01','RH00' union all
select 2,'RH02','RH01' union all
select 3,'RH03','RH01' union all
select 4,'RH04','RH03' union all
select 5,'RH05','RH02' union all
select 6,'RH06','RH03' union all
select 7,'RH07','RH04' union all
select 8,'RH08','RH02' union all
select 9,'RH09','RH05'
GO
-- Table valued Function
GO
create function GetChild (@Id INT)
RETURNS @temp TABLE (RefId varchar(10))
AS
BEGIN
declare @tempDependencies table (Id int)
insert into @tempDependencies SELECT @Id
WHILE ((Select COUNT(Id) from hierarchy where FromRefId in (select RefId from hierarchy where id in (select Id from @tempDependencies)) and id not in (select Id from @tempDependencies)) > 0)
BEGIN
insert into @tempDependencies
Select Id from hierarchy where FromRefId in (select RefId from hierarchy where id in (select Id from @tempDependencies)) and id not in (select Id from @tempDependencies)
END
insert into @temp
Select RefId from hierarchy where FromRefId in (select RefId from hierarchy where id in (SELECT Id from @tempDependencies))
return
END
GO
-- You may call the functions like this:
select * from GetChild(1)
select * from GetChild(2)
select * from GetChild(3)
SQL Fiddle Code
你的意思是FromRefId? – Nikolaus
这并不容易理解,为什么你想要查询这个结果!你可以解释吗? – Nikolaus
不,我想REFID RH02 RH03 RH04 RH05 RH06 RH07 RH08 RH09 –