SQL Server沒有像oracle中那樣可以很方便的尋找上下級的層次搜尋的方法。我嘗試使用了一個預存程序來實現該功能,預存程序是以前看到別人寫過類似的拿來改的。
create proc getParentType (@type_id int)
as
begin
declare @tmp1 table ([ID] int, type_name varchar(100), parent_type_id int)
declare @tmp2 table ([ID] int, type_name varchar(100), parent_type_id int)
declare @tmp3 table ([ID] int, type_name varchar(100), parent_type_id int)
insert @tmp1 select * from TD_Type where [type_id]=@type_id
insert @tmp2 select * from TD_Type where [type_id]=@type_id
while (select count(*) from @tmp2)>0
begin
insert @tmp1 select * from TD_Type where type_id in (select [parent_type_id] from @tmp2)
insert @tmp3 select * from @tmp2
delete @tmp2
insert @tmp2 select * from TD_Type where type_id in (select [parent_type_id] from @tmp3)
delete @tmp3
insert @tmp1 select * from TD_Type where type_id in (select [parent_type_id] from @tmp2)
end
end
select distinct(id), type_name, parent_type_id from @tmp1
GO
------------------執行
exec getParentType 10015