0

I have a BIRT report with a data set using the following query

select id, parentId from objectTable where id=?

The id used in the query is passed in through a BIRT parameter and based on the results I get I want to find the parentObject. After the above query is executed I want to check if a parentObject exists and do this by checking the parentId value from the query above and if it's not zero there is a parent object. So somehow I need to say

while (parentId > 0)
    select id, parentId from objectTable where id=parentId

Then I need to continue looping until the parentId is zero and I know I have the greatest ancestor.

Is there a way to use Javascript on the dataset to do this? or possibly a nested sql statement that will allow me to do something like this?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
user2687482
  • 215
  • 3
  • 17

1 Answers1

1

A recursive CTE can do that for you in a single query:

WITH RECURSIVE cte AS (
   SELECT id, parentid
   FROM   objecttable
   WHERE  id = ?

   UNION ALL
   SELECT o.id, o.parentid
   FROM   cte c
   JOIN   objecttable o ON o.id = c.parentid
   WHERE  c.parentid > 0
   )
SELECT *
FROM   cte
WHERE  parent_id = 0;

A single round-trip to the db server is typically much cheaper.
Closley related case:
Tree Structure and Recursion

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228