--------------------
declare @collect table ( catid int, tlevel int )
insert into @collect values (3,1)
declare @count int
set @count = 2
declare @maxlevel int
set @maxlevel = 2
while ((select count(1) from @collect where tlevel = @count-1) > 0 and @count <= @maxlevel)
begin
insert into @collect
select c.categoryid, @count
from category c inner join @collect b on c.parentcategoryid = b.catid and b.tlevel = @count-1
set @count = @count + 1
end
select * from @collect order by tlevel
--------------------
--------------------
CREATE PROCEDURE [dbo].[GetCategoryTree]
-- Add the parameters for the stored procedure here
@ParentCategoryID int
AS
BEGIN
-- the category id's to be output
declare @collect table ( catid int, tlevel int )
insert into @collect values (3,1)
-- a loop counter used to limit the depth we go to
declare @count int
set @count = 2
-- the deepest level to go to
declare @maxlevel int
set @maxlevel = 2
-- the loop to collect category id's
while
(
(select count(1) from @collect where tlevel = @count-1) > 0 -- keep going while we have categories
and @count <= @maxlevel -- keep going until the max level depth is reached
)
begin
-- insert the categories where the previous level contains the parent ids of the current level
insert into @collect
select c.categoryid, @count
from category c inner join @collect b on c.parentcategoryid = b.catid and b.tlevel = @count-1
-- increment the level being collected
set @count = @count + 1
end
-- return the found category id's
select * from @collect order by tlevel
END
--------------------
No comments:
Post a Comment