1

我正在使用一个函数,并希望收到这样的字符串:如您所见,它可能是“n 次”嵌套的。

<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 到目前为止:

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;

这让我回到了第一个“级别”。但在这个循环中,我想为数据库中的每个条目创建另一个循环,这样我就可以接收上面的 xml 字符串。

数据库如下所示:

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

如何循环遍历它,直到表中没有更多数据并继续下一个级别?

谢谢你帮助马特

4

1 回答 1

2

使用分层查询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;

为了确保根节点先出现,然后是子节点,您可以像这样扩展语句:

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;

这是一个 SQLFiddle:http ://sqlfiddle.com/#!4/606a7/1

于 2013-09-04T11:18:39.040 回答