If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > DB2 > Common Table Expressions (CTE) Question

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 02-18-07, 15:48
raysefo raysefo is offline
Registered User
 
Join Date: Dec 2006
Posts: 17
Common Table Expressions (CTE) Question

Hi,

ID NAME PARENTID
1 ABC
2 Sales 1
3 Avdertisement 2
4 Accounting 1
5 DEF
...

Select name from [mytable] where ID = 1

if ID = 1 than NAME is ABC
if ID = 2 than NAME is ABC/Sales
if ID = 3 than NAME is ABC/Sales/Advertisement
if ID = 4 than NAME is ABC/Accounting
and
if ID = 5 than NAME is DEF

How can i do a generic SELECT statement to do the sample above?
But above is just a sample, there may be 5 sub departments, may be 100.

I got the code for SQL 2005 but i need DB2 v 8.

Try this (SQL 2005 only):


Declare @ID int, @Dept varchar(max)
Set @ID = 3;

With DeptHier(ID, ParentID)
as
(
Select ID, ParentID
From Dept
Where ID = @ID

union all

Select Dept.ID, Dept.ParentID
From Dept JOIN DeptHier
On Dept.ID = DeptHier.ParentID
)
Select @dept = Coalesce(@dept + '/', '') + d.Name
from Dept d Join DeptHier dh
on d.ID = dh.ID
order by dh.ParentID

select @dept as Dept
Reply With Quote
  #2 (permalink)  
Old 02-20-07, 08:38
ARWinner ARWinner is offline
Registered User
 
Join Date: Jan 2003
Posts: 3,575
Look in Graeme Birchall's DB2 Cookbook under recursion. This should help you.

http://mysite.verizon.net/Graeme_Birchall/id1.html

Andy
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On