Click here to Skip to main content
15,880,543 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
G007 AFFILATES HOULD RETURN ALL DIRECT SUB AND SUB TO SUB LEVEL AFFILIATES.
CAN BE TO NTH LEVEL

HOW TO QUERY in DB2?


AREVA_COMPANIES
---------------------------
COMPANY_CODE|AFFILIATE_CODE
G007        |K001
G007        |K002
G007        |K003
G007        |K004
K001        |K010
K001        |K011
K001        |K012
K002        |K020
K002        |K031
K004        |K067


What I have tried:

WITH ALL_AFFILIATES(COMPANY_CODE,AFFILIATE_CODE) AS
(
 SELECT COMPANY_CODE, AFFILIATE_CODE
 FROM   AREVA_COMPANIES
 WHERE  COMPANY_CODE = 'G007'
 UNION ALL
 SELECT B.COMPANY_CODE, B.AFFILIATE_CODE
 FROM   AREVA_COMPANIES B , ALL_AFFILIATES A
 WHERE  B.COMPANY_CODE = A.AFFILIATE_CODE
)
SELECT COMPANY_CODE, AFFILIATE_CODE
FROM ALL_AFFILIATES
Posted
Updated 27-Jun-19 23:17pm
Comments
Patrice T 28-Jun-19 0:50am    
What is the problem with your query ?
Member 12613458 3-Jul-19 1:32am    
Getting a timout error in DB2
DB2 "00C90084", type of resource: "00000100", and resource name: "DSNDB07". SQLSTATE=57011

THere is a row
AREVA_COMPANIES
---------------------------
COMPANY_CODE|AFFILIATE_CODE
G007 |G007

Could that be the reason? Please help.
Patrice T 3-Jul-19 2:15am    
Use Improve question to update your question.
So that everyone can pay attention to this information.

1 solution

Although UNION will work as you have demonstrated in your query, it is not extensible to the nth level.

You essentially need to traverse a hierarchy - I have given an example here - Processing Loops in SQL Server[^]

The example uses T-SQL which DB2 largely follows. It's been a long time since I used DB2 but it does support recursive CTEs - see CTE - IBM Knowledge Center[^] and How to do a Recursive Query - IBM Knowledge Center[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900