mcgrcoAgain
Registered User.
- Local time
- Today, 13:39
- Joined
- Jan 26, 2006
- Messages
- 47
Hi,
Im new to sql server so please forgive me if this question is obvious.
Any help is appreciative
what I'm trying to do is a recursive look up of child to ultimate parent.
The data is structured like so . if I look up child 2-4 I want to return sub Parent 2
child sub Parent Ultimate Parent
1
2 2 1
3 2 1
4 2 1
--**code as follows. this only returns the first record
DECLARE @CHILD_PROFIT_CENTRE varchar(20)
SET @CHILD_PROFIT_CENTRE = 'SIH' --ultimate parent code
create table #CTE_Example
(
CHILD_PROFIT_CENTRE varchar(20)
,CHILD_PROFIT_CENTRE_DESC varchar(100)
,PARENT_PROFIT_CENTRE varchar(100)
,Depth float
)
insert into #CTE_Example (CHILD_PROFIT_CENTRE, CHILD_PROFIT_CENTRE_DESC, PARENT_PROFIT_CENTRE, Depth)
SELECT A.CHILD_PROFIT_CENTRE, A.CHILD_PROFIT_CENTRE_DESC, A.PARENT_PROFIT_CENTRE, 0 AS Depth
FROM STAGING_SIH..SIHFEEDS_SAP_PCHIERARCHY A
WHERE A.CHILD_PROFIT_CENTRE = @CHILD_PROFIT_CENTRE
UNION ALL
SELECT A.CHILD_PROFIT_CENTRE, A.CHILD_PROFIT_CENTRE_DESC, A.PARENT_PROFIT_CENTRE, #CTE_Example.Depth + 1 AS Depth FROM STAGING_SIH..SIHFEEDS_SAP_PCHIERARCHY A
JOIN #CTE_Example ON A.PARENT_PROFIT_CENTRE= #CTE_Example.PARENT_PROFIT_CENTRE
SELECT * FROM #CTE_Example
Im new to sql server so please forgive me if this question is obvious.
Any help is appreciative
what I'm trying to do is a recursive look up of child to ultimate parent.
The data is structured like so . if I look up child 2-4 I want to return sub Parent 2
child sub Parent Ultimate Parent
1
2 2 1
3 2 1
4 2 1
--**code as follows. this only returns the first record
DECLARE @CHILD_PROFIT_CENTRE varchar(20)
SET @CHILD_PROFIT_CENTRE = 'SIH' --ultimate parent code
create table #CTE_Example
(
CHILD_PROFIT_CENTRE varchar(20)
,CHILD_PROFIT_CENTRE_DESC varchar(100)
,PARENT_PROFIT_CENTRE varchar(100)
,Depth float
)
insert into #CTE_Example (CHILD_PROFIT_CENTRE, CHILD_PROFIT_CENTRE_DESC, PARENT_PROFIT_CENTRE, Depth)
SELECT A.CHILD_PROFIT_CENTRE, A.CHILD_PROFIT_CENTRE_DESC, A.PARENT_PROFIT_CENTRE, 0 AS Depth
FROM STAGING_SIH..SIHFEEDS_SAP_PCHIERARCHY A
WHERE A.CHILD_PROFIT_CENTRE = @CHILD_PROFIT_CENTRE
UNION ALL
SELECT A.CHILD_PROFIT_CENTRE, A.CHILD_PROFIT_CENTRE_DESC, A.PARENT_PROFIT_CENTRE, #CTE_Example.Depth + 1 AS Depth FROM STAGING_SIH..SIHFEEDS_SAP_PCHIERARCHY A
JOIN #CTE_Example ON A.PARENT_PROFIT_CENTRE= #CTE_Example.PARENT_PROFIT_CENTRE
SELECT * FROM #CTE_Example