Hierarchical queries and nested tables

Hallo,
Assume you have the following data structure:
SQL> desc mgr
Name Null? Typ
MGRNO NUMBER
LASTNAME VARCHAR2(20)
EMPS EMPTYPE_TAB
SQL> desc emptype_tab
emptype_tab TABLE OF EMP_TYPE
Name Null? Typ
EMPNO NUMBER
LASTNAME VARCHAR2(20)
I would like to select rows in a hierarchical order to get an output like this:
LAST_NAME EMPNO MGRNO LEVEL
King 100 1
Cambrault 148 100 2
Bates 172 148 3
..but i have absolutely no clue how to use the hierarchical query clause with a nested table.
can anybody help me?

scott@ORA92> CREATE OR REPLACE TYPE emp_type AS OBJECT
  2    (empno      NUMBER,
  3       lastname VARCHAR2(20))
  4  /
Type created.
scott@ORA92> CREATE OR REPLACE TYPE emptype_tab AS TABLE OF emp_type
  2  /
Type created.
scott@ORA92> CREATE TABLE mgr
  2    (MGRNO      NUMBER,
  3       LASTNAME VARCHAR2(20),
  4       EMPS      EMPTYPE_TAB)
  5    NESTED TABLE emps STORE AS emps_nt
  6  /
Table created.
scott@ORA92> INSERT INTO mgr VALUES (NULL, NULL, emptype_tab (emp_type (100, 'King')))
  2  /
1 row created.
scott@ORA92> INSERT INTO mgr VALUES (100, 'King', emptype_tab (emp_type (148, 'Cambrault')))
  2  /
1 row created.
scott@ORA92> INSERT INTO mgr VALUES (148, 'Cambrault', emptype_tab (emp_type (172, 'Bates')))
  2  /
1 row created.
scott@ORA92> SELECT * FROM mgr
  2  /
     MGRNO LASTNAME
EMPS(EMPNO, LASTNAME)
EMPTYPE_TAB(EMP_TYPE(100, 'King'))
       100 King
EMPTYPE_TAB(EMP_TYPE(148, 'Cambrault'))
       148 Cambrault
EMPTYPE_TAB(EMP_TYPE(172, 'Bates'))
scott@ORA92> SELECT m.mgrno, m.lastname as mgr, e.empno, e.lastname as emp
  2  FROM   mgr m, TABLE (emps) e
  3  /
     MGRNO MGR                       EMPNO EMP
                                       100 King
       100 King                        148 Cambrault
       148 Cambrault                   172 Bates
scott@ORA92> SELECT lastname, empno, mgrno, LEVEL
  2  FROM   (SELECT m.mgrno, e.lastname, e.empno
  3            FROM   mgr m, TABLE (emps) e)
  4  START  WITH mgrno IS NULL
  5  CONNECT BY PRIOR empno = mgrno
  6  /
LASTNAME                  EMPNO      MGRNO      LEVEL
King                        100                     1
Cambrault                   148        100          2
Bates                       172        148          3
scott@ORA92>

Similar Messages

  • SQL Loader Constraints with Column Objects and Nested Tables

    I am working on loading a Table that (god forbid) contains columns, column objects, and nested tables (which contains several depth of column objects). My question is does SQL Loader have a hidding undocumented feature where it states how the column objects must be grouped in refereneced to the nested tables within the loader file? I can load the various column objects, and nested tables fine right now, however, I am loading them all in strange and insane order. Can anyone answer this question? Thanks.
    Peter

    I just noticed that my email is wrong. If you can help, plese send email to [email protected]
    thanks.

  • OCI doc says Cursor and Nested table have the same bind type SQLT_RSET but they don't

    5 Binding and Defining in OCI
    PL/SQL REF CURSORs and Nested Tables in OCI
    says SQLT_RSET is passed for the dty parameter.
    If I use SQLT_RSET for the return value of a function that returns a table and pass a statement handle's address for the OCI parameter data pointer, I expected that the statement handle will be instantiated as a result of executing the function on which I can further perform fetch, similar to a cursor. But it throws exception PLS-00382: expression is of wrong type ORA-06550: line 2, column 3. Is the above documentation wrong?
    From the OCI header file I see that for varray and nested table it mentions to use SQLT_NCO. I could find no example in the OCI documentation on how to pass or receive as return value a nested value when using SQLT_NCO.
    Please help before I shoot myself.

    So the Nested table I quoted in the doc is not actually used to mean a table type below?
    create type t_resultsetdata as object (
    i int, d decimal, c varchar(10)
    create type t_nested_resultsetdata as table of t_resultsetdata;
    create function Blah return t_nested_resultsetdata  is . . .
    For this you are saying to use SQL_NTY and not SQL_NCO. Can you tell where this usage is documented, because ocidfn.h says
    #define SQLT_NTY  108                              
    /* named object type */
    #define SQLT_NCO  122 
    /* named collection type (varray or nested table) */
    Another question - Because of the original document I said I followed, I thought I could treat cursor and nested table similarly in the calling application, i.e. I could repeatedly do a fetch on the OCIStmt* which will be bound for nested table. Now from what you say I understand I can't really bind a OCIStmt* for nested table but have an object type. That means it will get all the data of that collection in one go, right? LIke I said, lack of examples is making this tough. I don't want to look into OCI source code, as that will be too much.

  • Sql*loader and nested tables

    I'm having trouble loading a nested table via sqlldr in Oracle 10g and was hoping someone could point me in the right direction. I keep getting the following error:
    SQL*Loader-403: Referenced column not present in table mynamespace.mytable
    Here's an overview of my type and table definitions:
    create type mynamespace.myinfo as object
    i_name varchar2(64),
    i_desc varchar2(255)
    create TYPE mynamespace.myinfotbl as TABLE of mynamespace.myinfo;
    create table mynamespace.mytable
    Info mynamespace.myinfotbl,
    note varchar2(255)
    NESTED TABLE Info STORE AS mytable_nested_tab;
    My control file looks like this:
    load data
    infile 'mydatafile.csv'
    insert into table mynamespace.mytable
    fields terminated by ',' optionally enclosed by '"'
    TRAILING NULLCOLS
    Info nested table count(6)
    Info column object
    i_name char(64),
    i_desc char(255)
    note
    Example mydatafile.csv would be something like:
    lvl1,des1,lvl2,des2,lvl3,des3,lvl4,des4,lvl5,des5,lvl6,des6,a test data set
    I can't figure out why sqlldr keeps rejecting this control file. I'm using 'direct=false' in my .par file.
    Any hints?

    I just noticed that my email is wrong. If you can help, plese send email to [email protected]
    thanks.

  • Apex, Tabular forms and Nested Tables := Headache

    Hi All,
    I'm constructing an Apex aplication for Performance Reviewing staff and I have need of nested tables within each line item for ongoing comments during the year, the headings of which are drawn from another table, based on a template for which ones are to be used at any given time.
    I'd like to be able to use a tabular form to draw out the history of comments at any given time and modify them however I'm at a complete loss as to how to get this working with a tabular form in Apex. If anyone could point me at some good documentation on the subject or even suggest a better method to get this done I'd be very grateful.
    Thanks!

    Hi,
    Take a look at this article:
    http://www.oracle-base.com/articles/misc/ObjectViewsAndNestedTables.php
    First, create a view as described on your nested and other table(s), with 'Instead Of' triggers handling the DML. Next create the tabular form based on the view. You'll find many posts in the forum regarding building a tablular form based on a view.
    Paul Brookes.

  • Hierarchal queries and USER_DEPENDENCIES

    I'm new to Hierarchal queries; I have a Hierarchal query on USER_DEPENDENCIES that does not work and gives an error
    'TSPKG_ES' is a package the works; I'm trying to do query to see what is calls
    SELECT LEVEL, D.*
    FROM DBA_DEPENDENCIES D
    START WITH D.name = 'TSPKG_ES'
    CONNECT BY PRIOR D.name = D.referenced_name
    Result = ORA-00600: internal error code, arguments: [sorsikbeg_1], [5], [0] ,[],[],[],[],[]
    SELECT LEVEL, D.*
    FROM DBA_DEPENDENCIES D
    START WITH D.name = 'DATATESTSPKG_ES'
    CONNECT BY PRIOR D.referenced_name = D.name
    Result = ORA=0143: CONNECT BY loop in user data

    OS = Microsoft Windows XP V2002 Service Pack 3
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
    PL/SQL Release 10.2.0.4.0 - Production
    "CORE     10.2.0.4.0     Production"
    TNS for 64-bit Windows: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - Production

  • How to insert array of records in Storage table and  Nested table same time??

    Hi,
    I am using ProC++ ( Oracle 8i) . I want to insert a host array
    in a table. That table has a nested table in it. So for every
    record in my host array, there are muliple records to be
    inserted in Nested table. How is this possible using pro*C??
    Pls help.
    Thanks
    Nivedita

    Have a look at the Oracle 9i PL/SQL manual, which has an example.

  • DB Link and nested tables

    Is there any way of passing a PL/SQL nested table (IS TABLE OF xxx) when calling a procedure or package across a DB Link in 9i? It does not appear to be possible due to the limitation on use of user types.
    Thanks

    I would be inclined to discourage you from using nested tables in almost any context. What is the business problem you are trying to solve?
    Not coding problem ... business problem.
    Perhaps we can suggest a better way to approach the problem.

  • SELECT, hierarchical queries and JOIN

    Hi everyone,
    I have a small SELECT statement but I can't find an easy solution.
    Look at this situation:
    drop table departments;
    CREATE TABLE departments
      dpt_id NUMBER(10) UNIQUE,
      dpt_name VARCHAR2(100),
      dpt_parent_id NUMBER(10)
    TRUNCATE table departments;
    INSERT INTO departments VALUES(1, 'Company', null);
    INSERT INTO departments VALUES(2, 'HR', 1);
    INSERT INTO departments VALUES(3, 'SALES', 1);
    INSERT INTO departments VALUES(4, 'IT', 1);
    INSERT INTO departments VALUES(222, 'Helpdesk', 4);
    INSERT INTO departments VALUES(223, 'French Speaking', 222);
    INSERT INTO departments VALUES(224, 'Another level', 223);
    INSERT INTO departments VALUES(5, 'LEGAL', 1);
    INSERT INTO departments VALUES(66, 'Recruitment', 2);
    INSERT INTO departments VALUES(33, 'Logistics', 2);
    INSERT INTO departments VALUES(39, 'Fleet management', 33);
    INSERT INTO departments VALUES(31, 'Local Sales', 3);
    INSERT INTO departments VALUES(60, 'European Sales', 3);
    INSERT INTO departments VALUES(61, 'Germany', 60);
    INSERT INTO departments VALUES(62, 'France', 60);
    INSERT INTO departments VALUES(620, 'Paris', 62);
    INSERT INTO departments VALUES(621, 'Marseilles', 62);
    INSERT INTO departments VALUES(38, 'American Sales', 3);
    INSERT INTO departments VALUES(34, 'Asian Sales', 3);
    CREATE table persons
      person_id NUMBER(10) UNIQUE,
      person_name VARCHAR2(100),
      person_dpt_id NUMBER(10)
    truncate table persons;
    INSERT INTO persons VALUES(1, 'Jim', 2);
    INSERT INTO persons VALUES(2, 'Jack', 621);
    INSERT INTO persons VALUES(3, 'John', 620);
    INSERT INTO persons VALUES(4, 'John', 224);
    INSERT INTO persons VALUES(5, 'Fred', 61);It's a simple hierachy like the one we can find in HR schema. The link between an department and its parent is with parent id. THe following statement build the whole tree:
    SELECT dpt_id, level, LPAD(' ', LEVEL-1)|| dpt_name
      FROM departments
    START WITH dpt_parent_id IS NULL
    CONNECT BY dpt_parent_id = PRIOR dpt_id;As you can see in the script above, I have a few people assigned to these departments. It's also a classic situtation...
    I would like to have something like this:
    WITH temp AS
      SELECT dpt_id, dpt_name, SYS_CONNECT_BY_PATH(dpt_name, '#') as full_path
        FROM departments
       START WITH dpt_parent_id IS NULL
    CONNECT BY dpt_parent_id = PRIOR dpt_id
    SELECT p.person_name, d.dpt_name, --d.full_path,
           regexp_substr(d.full_path, '[^#]+', 1, 2, 'i') as t1,
           regexp_substr(d.full_path, '[^#]+', 1, 3, 'i') as t2,
           regexp_substr(d.full_path, '[^#]+', 1, 4, 'i') as t3,
           regexp_substr(d.full_path, '[^#]+', 1, 5, 'i') as t4
      FROM persons p
      JOIN temp d ON d.dpt_id = p.person_dpt_id;This is the exact output I want, but I wonder... Is it possible to do it without the factored sub-query? It's nice and works fine but I had to precompute the whole path to split it again. I mean, this should be possible in one step. Any suggestion?
    I'm using Oracle 10g
    Thanks,

    Hi,
    user13117585 wrote:
    ... But sometimes, I just find the statements difficult for what they do. For example, my previous one. I have a person, and I want to see his department and the path in the tree.Actually, you want more than that; you want to parse the path, and display each #-delimited part in a separate column. If you didn't want that, then you could do away with the 4 REGEXP_SUBSTR calls, like this:
    WITH temp AS
      SELECT dpt_id, dpt_name
      ,       SUBSTR ( REPLACE ( SYS_CONNECT_BY_PATH ( RPAD (dpt_name, 15)     -- Using 15 just for demo
               , 16
               )     as full_path
        FROM departments
       START WITH dpt_parent_id IS NULL
    CONNECT BY dpt_parent_id = PRIOR dpt_id
    SELECT p.person_name, d.dpt_name, d.full_path
      FROM persons p
      JOIN temp d ON d.dpt_id = p.person_dpt_id;Output:
    PERSON_N DPT_NAME      FULL_PATH
    Jim      HR            HR
    Fred     Germany       SALES          European Sales Germany
    John     Paris         SALES          European Sales France         Paris
    Jack     Marseilles    SALES          European Sales France         Marseilles
    John     Another level IT             Helpdesk       French SpeakingAnother levelAs you can see, full_path is one giant column, but it's formatted to look like 4 separate columns, forresponding to your original t1, t2, t3 and t4. I limited the output to 15 characters, just for debugging and posting purposes. You can use any number of characters you like.
    It's too complex for this simple thing.It would be nice if there was something simpler that did exactly what you wanted, but I'm not sure it's reasonable to expect it in every case. I asked a lot of questions in my first message, but I'm not sure you've tried to answer any of them, so I'm not sure why you're unhappy with the query you posted. I can think of lots of ways to change the query, but I have no way of telling if you would like them any better than what you already have.
    And hopefully, I know where to start in the hierarchy and I know where to stop. If I had to show all the levels and have one column by level dynamically, I'd be stuck. Sorry, I don't understand this part.
    Are you saying that it seems inefficient to generate the entire tree, when perhaps few of the nodes will have have matches in the persons table? If so, you can invert the whole query. Instead of doing the CONNECT BY first and then joining, do the join first and then the CONNECT BY. Instead of doing a top-down CONNECT BY, where you start with the parentless nodes (whether or not you'll ultimately need them) and then find their descendants, do a bottom-up CONNECT BY, where you start with the nodes you know you'll need, and then find their ancestors.
    I just find it difficult for such a simple need. Again, there are lots of things that could be done. If you won't say what you want, that makes it hard for me to tell you how to get it. All that I've picked up for sure is that you don't like doing a sub-query. That's unfortunate, because sub-queries are so basic. They have very important been since Oracle 8.1, and they don't seem to be going away. Quite the opposite, in fact. You need sub-queries for all kinds of things, not just CONNECT BY. To give just a couple of examples, they're the only thing that make analytic functions really useful, and they simplfy chasm traps (basically, multiple 1-to-many relationships on the same table) considerably. I'm sorry if you don't lke sub-queries, but I don't see how you can work in this field and not use them.
    Edited by: Frank Kulash on Nov 15, 2011 3:18 PM
    Revised query

  • Query hangs using db link and nested table collection

    Hi,
    I have a stored procedure which takes, as input, a string of values that can vary in length. The input is used as an IN operator within the queries that exist within the proc:
    Code:
    PROCEDURE get_contacts (i_customerids IN VARCHAR2)
    an example of the input would be: '987451',412897' or '7541256','75412','95412589'
    In order to process the dynamic "In-List", I created a custom collection type to convert the string to a table:
    Code:
    CREATE OR REPLACE
    TYPE stringtotable AS TABLE OF VARCHAR2(3900)
    (I've also tried the solutions on http://tkyte.blogspot.com/2006/06/varying-in-lists.html and http://fdegrelle.over-blog.com/article-1694534-6.html for handling dynamic in-lists and they also hang)
    The proc contains 2 queries, the first returns records from a table within the current database:
    Code:
    SELECT *
    FROM contacts
    WHERE customer_id IN (
    SELECT *
    FROM TABLE (stringtotable (i_customerids
    The second query returns records from a database that is defined via a db link:
    Code:
    SELECT b.customer_id, a.row_id, a.fst_name, a.last_name
    FROM userlist.customers@uldblink a, userlist.firms@ulbdlink b
    WHERE a.parent_id = b.row_id
    AND b.customer_id IN (
    SELECT *
    FROM TABLE (stringtotable (i_customerids
    The first query is executing without issue. The second query, however, is hanging indefinitely. Additionally, If I hard code the string in the IN operator, the second query executes without issue.
    I am not the DBA for the database, so I don't currently have access to the trace logs. I've requested access to the trace logs to see if I can figure out what is hanging.
    In the meantime, I was hoping someone would be able to tell me if
    a: there is a better way to handle "dynamic in- lists".
    or
    b: if there is something obvious that I'm not considering.
    Thanks for your help,
    Fielding
    Message was edited by:
    fwilson

    Hi Todd,
    Thanks for the suggestion. I was not aware of the cardinality hint.
    I tried adding it to my query but unfortunately the query still appeared to hang. It did get me thinking though... that maybe the stringtotable collection type is creating the table in memory, and therefore its records aren't accessible to the dblink
    so I inserted the values that were being returned via the stringtotable collection type into a physical table named TestTable. I then modified my query to select the values from TestTable.
    Code:
    ...in (select /*+ cardinality(t 3) */ t.*
    from testtable t)
    This worked.
    So that poses the questions-
    a: is my assumption about the in-memory table correct
    and
    b: if so is there a way around it?
    Thanks for your help

  • Hierarchical queries and referential constraints

    Experts,
    What is the rationale for having a referential integrity constraint on a table that has rows bound by hierarchical relationships ?? The hierarchical relationship ensures that each row is referencing another in the same table via the PRIOR clause. If I add a foreign key relationship to these columns , does it make any sense ??/
    -Rekha

    but you can use a hierarchical query to display constraints in a tree !
    SQL> create table t1 (a number primary key);
    Table created.
    SQL> create table t2 (b number primary key, a number references t1(a));
    Table created.
    SQL> create table t3 (c number primary key, b number references t2(b));
    Table created.
    SQL> create table t4 (d number primary key, a number references t1(a));
    Table created.
    SQL> create table t5 (e number primary key, f number references t5(e));
    Table created.
    SQL> select sys_connect_by_path(p.table_name,':')||':'||r.table_name p
    from all_constraints p
        join all_constraints r
        on (p.constraint_name = r.r_constraint_name and p.owner = r.r_owner)
    where CONNECT_BY_ISLEAF = 1
    connect by nocycle prior r.table_name = p.table_name
    start with p.table_name not in (select r.table_name from all_constraints p join
    all_constraints r on (p.constraint_name = r.r_constraint_name and
    p.owner = r.r_owner and p.table_name != r.table_name) );
    :DEPT:EMP
    :T1:T4
    :T1:T2:T3
    :T5:T5

  • Slow queries and full table scans in spite of context index

    I have defined a USER_DATASTORE, which uses a PL/SQL procedure to compile data from several tables. The master table has 1.3 million rows, and one of the fields being joined is a CLOB field.
    The resulting token table has 65,000 rows, which seems about right.
    If I query the token table for a word, such as "ORACLE" in the token_text field, I see that the token_count is 139. This query returns instantly.
    The query against the master table is very slow, taking about 15 minutes to return the 139 rows.
    Example query:
    select hnd from master_table where contains(myindex,'ORACLE',1) > 0;
    I've run a sql_trace on this query, and it shows full table scans on both the master table and the DR$MYINDEX$I table. Why is it doing this, and how can I fix it?

    After looking at the tuning FAQ, I can see that this is doing a functional lookup instead of an indexed lookup. But why, when the rows are not constrained by any structural query, and how can I get it to instead to an indexed lookup?
    Thanks in advance,
    Annie

  • Using nested tables and varrays in Forms/Reports6i

    Hi! Could anybody give practical examples of applications based on nested tables and varrays in Forms/Reports6i.
    The possible schema of building user interface and so on.
    Thank you.
    [email protected]

    Hi,
    Varrays and nested tables are not supported within Forms6i and Reports6i. This means tare is no way to use it.
    Frank

  • Problem with generating xml and nested cursor (ora-600)

    I have a problem with generating xml (with dbms_xmlquery or xmlgen) and nested cursors.
    When I execute the following command, I get a ORA-600 error:
    select dbms_xmlquery.getxml('select mst_id
    , mst_source
    , cursor(select per.*
    , cursor(select ftm_fdf_number
    , ftm_value
    from t_feature_master
    where ftm_mstr_id = pers_master_id ) as features
    from t_person per
    where pers_master_id = mst_id ) as persons
    from f_master
    where mst_id = 3059435')
    from dual;
    <?xml version = '1.0'?>
    <ERROR>oracle.xml.sql.OracleXMLSQLException: ORA-00600: internal error code, arguments: [kokbnp2], [1731], [], [], [], [], [], []
    </ERROR>
    The problem is the second cursor (t_feature_master).
    I want to generate this:
    <master>
    <..>
    <persons>
    <..>
    <features>
    <..>
    </features>
    </persons>
    <persons>
    <..>
    <features>
    <..>
    </features>
    </persons>
    </master>
    If i execute the select-statement in sql-plus, then I get the next result.
    MST_ID MST_SOURCE PERSONS
    3059435 GG CURSOR STATEMENT : 3
    CURSOR STATEMENT : 3
    PERS_MASTER_ID PERS_TITLE PERS_INITI PERS_FIRSTNAME PERS_MIDDL PERS_LASTNAME
    3059435 W. Name
    CURSOR STATEMENT : 15
    FTM_FDF_NUMBER FTM_VALUE
    1 [email protected]
    10 ....
    I use Oracle 8.1.7.4 with Oracle XDK v9.2.0.5.0.
    Is this a bug and do somebody know a workaround?

    Very simple...Drop all type objects and nested tables and create them again. You will get no error. I'll explain the reason later.

  • Inserting data with the help of nested table...!!!

    The following block is giving error
    ORA-06502: PL/SQL: numeric or value error
    the signature and signature_bkp have the same structure
    So, can anybody help me out to solve this issue :
    for copying records from one table to another table
    Thanking You advancely
    DECLARE
    CURSOR c1
    IS
    SELECT *
    FROM signature
    WHERE creation_time > TRUNC ( SYSDATE ) - 100
    AND ROWNUM < 102;
    TYPE sig_typ IS TABLE OF signature%ROWTYPE;
    sig_t sig_typ;
    BEGIN
    OPEN c1;
    FETCH c1
    BULK COLLECT INTO sig_t;
    CLOSE c1;
    FORALL i IN sig_t.FIRST .. sig_t.LAST
    INSERT INTO signature_bkp
    VALUES sig_t ( i );
    COMMIT;
    END;
    --DKar                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Or whether a INSERT statement with SELECT clause will do that for youby using this technique, it took 47:08:45 to copy 7252 rows
    and by using a cursor for loop took 49:03:23 to copy 13567 rows
    So there was appox. 40% increase in performance by using pl/sql. I thought it could be even faster using the bulk-bind ing features and nested tables.
    OR i just want to know ....how to correct the block of code that was given in my 1st msg without changing its logic.
    Thanks
    --DKar                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Maybe you are looking for