我有一個類似的答案 - 不過話說建它,我想它張貼;)
declare @Data table (
ID int not null,
Name varchar(50) not null,
ParentID int null
);
insert into @Data
select 1, 'Root', null
union select 2, 'Business', 1
union select 3, 'Finance', 1
union select 4, 'Stock', 3;
declare @UserInput int;
set @UserInput = 4;
with cParents as (
select d.ID, d.Name, d.ParentID
from @Data d
where d.ID = @UserInput
union all
select d.ID, d.Name, d.ParentID
from cParents c
inner join @Data d
on d.ID = c.ParentID
),
cChildren as (
select d.ID, d.Name, d.ParentID
from @Data d
where d.ID = @UserInput
union all
select d.ID, d.Name, d.ParentID
from cChildren c
inner join @Data d
on d.ParentID = c.ID
)
select RecordType='self', d.ID, d.Name, ParentName=isnull(p.Name,'')
from @Data d
left join @Data p
on p.ID = d.ParentID
where d.ID = @UserInput
union all
select RecordType='parents', d.ID, d.Name, ParentName=isnull(p.Name,'')
from cParents d
left join @Data p
on p.ID = d.ParentID
where d.ID <> @UserInput
union all
select RecordType='children', d.ID, d.Name, ParentName=isnull(p.Name,'')
from cChildren d
left join @Data p
on p.ID = d.ParentID
where d.ID <> @UserInput;
@Data代表樣本數據,@UserInput是輸入變量。 我添加了一個RecordType來闡明記錄部分的含義。 它在SQL Server 2008上測試過,應該可以在2005上運行 - 但不能在2000上運行。
基於該ID顯示列表的邏輯是什麼?我能看到的唯一模式是輸入ID在先。 – GONeale 2011-01-11 06:10:32
我有兩個關於父 - 子關係的表格需要顯示詳細記錄。我忘了告訴關於詳細信息表。希望你明白,爲什麼我需要這種類型的查詢 – shamim 2011-01-11 06:17:56
如何獲得結果與CTE – shamim 2011-01-11 09:23:57