您可以使用下面的方法。我寫了一個表值函數,「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 –