Hierarchical Query Needs to Pull Children, Parents and Siblings

本小妞迷上赌 提交于 2019-12-04 07:34:13

If your org. structure is strictly hierarchical, then you might use this approach: http://www.ibase.ru/devinfo/DBMSTrees/sqltrees.html

The drawback is that you have to update the index on every update of the org structure. However org structures are usually read much more often then modified. So IMHO this should do the trick.

The key to doing this is in the word "recursively". To do that, create a procedure that calls itself. This is an example for parents, but because it's using a cursor to scroll through entries, it should be straightforward for how to use this to find children and other relationships involving recursion.

CREATE OR REPLACE PROCEDURE find_parents( 
  org_id NUMBER, 
  lvl NUMBER DEFAULT 1) AS 

  c_parent table1.id%TYPE;
  c_name table1.name%TYPE;
  CURSOR c_parents (c_id table1.id%TYPE) IS
    SELECT parent, name FROM table1 WHERE (id = c_id);

  BEGIN
    dbms_output.put('-');
    OPEN c_parents(org_id);
    LOOP
      FETCH c_parents INTO c_parent, c_name;
      EXIT WHEN c_parents%notfound;
      dbms_output.put_line('Level ' || lvl || ' parent: [ID: ' || c_parent || ', NAME: ' || c_name || ']');
      find_parents(c_parent, lvl + 1);
    END LOOP;
    CLOSE c_parents;
  END;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!