Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

i need to create Function that will return the super parent of a given id from a table

the table look like table1 (id, parentId, someData) the parentId is related to the id

for example i have 1 - 2 - 3 - 4 id of each row

  • id parentId
  • 1 null
  • 2 1
  • 3 2
  • 4 3

now when i give the Function 4 as parameter it will return 1

i'm using SQL server 2008

how can this be done

share|improve this question
You will need a recursive CTE. Review this discussion for an example. – Nick Chammas Nov 21 '11 at 19:16
If you are still modelling the table, I suggest you take a look at the HeirarchyID datatype in SQL 2008. – datagod Nov 21 '11 at 19:29
I guess i will use this thanks – Alaa Jabre Nov 21 '11 at 19:45

Something like this

create table #table1 (id int, parentId int)

VALUES (1,null),
,(10, null)
declare @child int; 
set @child=4;
with prt as
(select 1 rn,id, parentid from #table1 where id=@child
union all
select rn+1 rn,,t.parentid from #table1 t join prt on
where t.parentid is not null
select top 1 parentid from prt order by rn desc

Recursive CTE

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.