parentid上的PLSQL循环



我正在使用一个函数,希望接收这样的字符串:正如您所看到的,它可能是"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 

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

谢谢你的帮助Matt

使用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

相关内容

  • 没有找到相关文章

最新更新