• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1438
  • Last Modified:

SQL SERVER 2000 Recursive Stored Procedure

Hello All,

Here is the scenario.

Name      CategoryID ParentID
Politics         1              0
Repub.         2              1
Bush            3              2
Democrat     4              1
Clinton         5              4
Cars            6              0
Chevy          7              6
Vette           8              7

It's your basic Parent-Child relationship.  
Politics is the the Parent to Republican and Democrat.
Republican is the parent to Bush
Democrat is the parent to Clinton.

well, I need a stored procedure that, with a given CategoryID, it will return me back a string
representing all of the children that belong to that specified categoryID in one field, in the form of something like,

if i specify Republican with a CategoryID=2 then:
Republican:2||Bush:3

if i specify Politics with a CategoryID=1 i would get returned:
Politics:1||Republican:2||Bush:3||Democrat:4||Clinton:5

One more twist to this would be that if i didn't specify a Category To Search Under,
It would return me back A Row for each Root Category with representation for the Child cateogories for that root. Like for instance,

If Category passed In = 0 then,
return back as many rows as there are root categories, so for the above example would return:

Politics:1||Republican:2||Bush:3||Democrat:4||Clinton:5
Cars:6||Chevy:7||Vette:8


I really don't mind of it's in a ad-hoc query to be put inside of a view, but a stored procedure would suit this type of query best.  Thanks ahead of time for the advice.

Flyin
0
flyin69
Asked:
flyin69
1 Solution
 
vc01778Commented:
You can do it like this:

-- Given

create table t1(Name varchar(20), CategoryID int, ParentID int)

insert into t1 values('Politics',        1,    0)
insert into t1 values('Repub.  ',      2  ,  1)
insert into t1 values('Bush    ',       3 ,   2)
insert into t1 values('Democrat',    4    ,1)
insert into t1 values('Clinton ',       5 ,   4)
insert into t1 values('Cars    ',       6 ,   0)
insert into t1 values('Chevy   ',      7  ,  6)
insert into t1 values('Vette   ',       8 ,   7)

The procedure will look like this:

===============================================
alter procedure traverse(@current int) as
 set nocount on
 declare @Name varchar(20), @CategoryID int, @level int, @result varchar(4000)
 declare @stack table(Name varchar(20), CategoryID int, level int)
 declare @tmp table(CategoryID int, Name varchar(4000))

 if @current > 0
   insert into @tmp values(@current, '')
 else
   insert into @tmp select CategoryID, '' as x from t1 where ParentID=0

 while 1 = 1 begin
   select top 1 @current = CategoryID from @tmp where len(Name) = 0
   if @@rowcount = 0 break
 
   insert into @stack select Name, CategoryID, 1
   from t1 where CategoryID=@current
 
   -- find all the children for a given CategoryID
   set @level = 1
   set @result=''
   while @level > 0
              begin
                  if exists (select 1 from @stack where level = @level)
                      begin
                          select top 1 @Name=Name, @CategoryID=CategoryID
                          from @stack
                          where level=@level
                          set @result = @result + case when len(@result)>0 then '||' else '' end
                                   + @Name + ':' + cast(@CategoryID as varchar)
                          delete from @stack
                          where level = @level and CategoryID = @CategoryID
                          insert into @stack
                          select Name, CategoryID, @level + 1
                          from t1
                          where ParentID = @CategoryID
                          if @@rowcount > 0 set @level= @level + 1
                      end
                  else
                      set @level = @level - 1
   end
   
   update @tmp set Name = @result where CategoryID=@current
 end

-- show the result
 select Name from  @tmp
============================================

Then you can call the proc so:

traverse 2

Repub.  :2||Bush    :3

---
traverse 1

Politics:1||Repub.  :2||Bush    :3||Democrat:4||Clinton :5

---
traverse 0

Politics:1||Repub.  :2||Bush    :3||Democrat:4||Clinton :5
Cars    :6||Chevy   :7||Vette   :8

VC
0
 
flyin69Author Commented:
Wow, that looks great VC, I'm gonna give that a try and give you some feedback.  Thanks for the expert piece of mind!

Flyin
0
 
flyin69Author Commented:
Amazing, thanks VC, that's exaclty what i was looking for!

I 've been looking for about 2 months now and finally on this site have seen the answer i was looking for.  thanks again.

Flyin
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Anthony PerkinsCommented:
>>Amazing, thanks VC, that's exaclty what i was looking for!<<
This is where you thank the Expert(s) helping you by awarding them the points.  See here for more info:
How do I accept a comment?
http://www.experts-exchange.com/help.jsp#hi68

Thanks.
0
 
flyin69Author Commented:
Thank you Ace
0
 
scottelkinCommented:
This is cleaner and probably faster:

create                    PROCEDURE ps_AllChildrenOfEmployee
 @categoryid int

AS

set nocount on

declare @rowcount int
 ,@qry varchar(1000)
 ,@template varchar(200)

--template that we will use to continue to nest sql statements
set @template = 'select categoryid from tblcategories where parentid in ( {0} )'

--used to store the query we will run each iteration
set @qry = 'select categoryid from tblcategories where parentid = ' + cast(@categoryid as varchar(5))

--we will get a list of all subordinates under this employee, no matter how deep
create table #temp(categoryid int)

--add themselves to the list of employees if you want
insert into #temp values(@categoryid)

--set rowcount to 1 so we can enter the loop
set @rowcount = 1

while @rowcount > 0
  begin
 --exec the last qry string. the first time through will run the default above
 exec ( 'insert into #temp ' + @qry )
 
 --get the # of records inserted.  if zero, then we want to exit the loop
 set @rowcount = @@rowcount

 --take this qry and nest it one more level deep so we get the next level down of employees
 set @qry = replace(@template,'{0}',@qry)

  end


drop table #temp
0
 
scottelkinCommented:
sorry, change all comments of "employee" to "category"
0
 
flyin69Author Commented:
wow thank you  scottelkin, i will try that out.  Yes it does look much cleaner!  I'll get back to you on how successful i was!
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now