我正在使用一个函数,并希望收到这样的字符串: 正如你所看到的,它可能是'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-string。
数据库看起来像:
| ID | PARENT_ID
----------------------
| 123 | NULL
| 12345 | 123
| 12333 | 123
| 123345 | 12333
| 1234 | NULL
如果表格中没有更多数据并继续下一个级别,我该如何循环播放?
谢谢你的帮助 马特
答案 0 :(得分: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