Domanda

I'm using a function and would like to receive a string like this: As you can see it could be 'n-times' nested.

<project id="123">
    <project id="12345" parentid="123"></project>
    <project id="12333" parentid="123>
        <project id="123345" parentid="12333"></project>
    </project>
</project>
<project id="1234">
     ...
</project>

PLSQL so far:

FOR i IN (   
        SELECT prj.ID AS PROJECT_ID, prj.PARENT_ID as PARENT_ID
        FROM PRJ_PROJECT prj 
        WHERE PARENT_ID IS NULL 
        )
LOOP
    sendXML := sendXML || '<project id="' ||  i.PROJECT_ID || '"' || ' parentid="' || i.PARENT_ID || '">' || '</project>';
END LOOP;

This returns me the first "level". But in this loop I want to have another loop, for each entry in the database, so I can receive the xml-string above.

The database looks like:

| ID     | PARENT_ID 
----------------------
| 123    | NULL 
| 12345  | 123 
| 12333  | 123
| 123345 | 12333 
| 1234   | NULL 

How can I loop through it until there is no more data in the table and go on with the next level?

Thanks for you help Matt

È stato utile?

Soluzione

Use a hierarchical query using connect by

SELECT prj.ID AS PROJECT_ID, 
       prj.PARENT_ID as PARENT_ID
FROM PRJ_PROJECT prj 
connect by prior prj.id = prj.parent_id
start with prj.PARENT_ID IS NULL;

To ensure that the root nodes come first, and then the children, you could extend the statement like this:

SELECT prj.ID AS PROJECT_ID, 
       prj.PARENT_ID as PARENT_ID,
       connect_by_root id as root_project_id
FROM PRJ_PROJECT prj 
connect by prior prj.id = prj.parent_id
start with prj.PARENT_ID IS NULL
order by connect_by_root id, level;

Here is an SQLFiddle: http://sqlfiddle.com/#!4/606a7/1

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top