Nested table variable intersect

Hi everyone,
I've created several nested tables of records, and I'd like to find the intersection of these variables. Just to use a a simple example:
declare
  type test_record is record (
    col1 NUMBER,
    col2 VARCHAR2(255)
  type n_table is table of test_record;
  t1 n_table;
  t2 n_table;
  t3 n_table;
begin
  t1(1).col1 := 1;
  t1(1).col2 := 'A';
  t1.extend;
  t1(2).col1 := 2;
  t1(2).col2 := 'B';
  t2(1).col1 := 1;
  t2(1).col2 := 'A';
  t2.extend;
  t2(2).col1 := 2;
  t2(2).col2 := 'B';
end;Now what I'd like to do is find the intersection of tables t1 and t2, and store it in t3. I've read about using multiset operators, but those only seem to work on nested tables of scalar types, not records. Is there any way I could do this? If it helps, I am only considering one column in my intersection, so if I could somehow select col1 from t1 and col1 from t2, and find the intersection of that sub-set, that might work too.
I'd also like to do it without looping through every row in every table, since the number of tables and number of rows can be quite large.
Thanks!

Hey Gerard, thanks for the reply.
The collections only exist in memory, not in the database. I'm running the same raw data through a series of different functions, each of which returns a collection with some rows removed. My desired output is the set of rows which exist in every collection, so the intersection.
I'm hesitant to change the type from a record to an object since the type is declared in a package and there's a lot of other procedures that use it. But you did get me thinking about using straight SQL. So I've made a table to use for temporary storage,
CREATE TABLE TEMP_STORAGE  (
    col1 NUMBER,
    col2 VARCHAR2(255)
)And now I can insert each collection into that table as they're made by the functions (with a normal for loop). Now when I want the intersection, I'm trying to write a query like:
declare
  type test_record is record (
    col1 NUMBER,
    col2 VARCHAR2(255)
  type n_table is table of test_record;
  t3 n_table;
  total_collections NUMBER;
begin
    total_collections := 4; --this number I won't know at design time, its a counter to see how many collections I've created and inserted into the temporary table
    select col1, col2 bulk collect into t3 from TEMP_STORAGE
        where count(col1) = total_collections;
end;So I want to count the number of duplicates in col1 for a row, and if there are enough, then select that row. I know I can't use the count function like that, is there another way I can do this without creating a seperate table for each function, and doing an intersect on all of them?
Thanks again for your quick response! If you need any clarification about what I'm doing or asking, please ask.

Similar Messages

  • NESTED TABLE BIND VARIABLE IN A REF CURSOR

    Hi,
    this works:
    open c_ref for v_sql using cp_asset_type
    where cp_asset_type is a nested tables passed into the proc as an 'in' parameter, but since the number of passed tables varies I loaded the nemes into an a nested table and tried the following:
    -- ELSIF BIND_COUNT.COUNT = 8 THEN
    -- OPEN C_REF FOR V_SQL
    -- USING BIND_COUNT(1),BIND_COUNT(2),BIND_COUNT(3),BIND_COUNT(4),BIND_COUNT(5),BIND_COUNT(6),BIND_COUNT(7),BIND_COUNT(8);     
    -- END IF;     
    which produced :
    ORA-22905 CANNOT ACCESS ROWS FROM A NON-NESTED TABLE ITEM
    my guess is that I'm passing the varchar2 names of the nested tables and the 'using' statement needs the actual table ????
    if this is true is there any way to pass a pointer for the bind variable nested tables?
    Thanks,
    Victor

    <br>i removed the AND...but m still getting the same error.
    <br>Is this a versioning problem...since urs is 9i and m using
    <br>Oracle8i Enterprise Edition Release 8.1.7.4.0
    <br> PROCEDURE sp_SearchByDriverName(i_C in varchar2,
    i_F in varchar2,
    i_LN in varchar2,
    i_FN in varchar2,
    o_Result out ABC_CURTYPE) is
    <br> tm_corp varchar2(2);
    <br> tm_fleet varchar2(6);
    <br> dc ABC_curtype;
    <br> begin
    <br> tm_c := getformattedc(i_C);
    <br> tm_f := getformattedf(i_f);
    <br> if i_FN is not null then
    <br> open dc for
    <br> SELECT distinct b.bus_ref_access_value,
    <br> i.individual_id,
    <br> br.mf_driver_last_name LN,
    <br> br.mf_driver_first_name FN,
    <br> substr(b.bus_ref_access_value, 4, 6) FLEET1,
    <br> (select '4444' from dual) --error is still coming here
    <br> FROM bus_ref_access_values b,
    <br> bus_ref_list brl,
    <br> individual i,
    <br> unit_contact_list f,
    <br> unit u,
    <br> bus_ref_current_prop br
    <br> WHERE b.bus_ref_id = br.bus_ref_id AND
    <br> b.bus_ref_id = brl.bus_ref_id AND
    <br> brl.reference_id = u.reference_id AND
    <br> u.unit_id = f.unit_id(+) AND
    <br> i.individual_id = f.individual_id AND
    <br> f.contact_type_ref = 'DR' AND
    <br> br.mf_driver_last_name like i_LN || '%' AND
    <br> br.mf_driver_first_name like i_FN || '%' AND
    <br> substr(b.bus_ref_access_value, 1, 2) = tm_c AND
    <br> substr(b.bus_ref_access_value, 4, 6) = tm_f AND
    <br> b.bus_ref_access_label = 'UNIT NUMBER'
    <br> ORDER BY 4, 3, 2;
    <br> close dc;
    <br>end if;

  • How to represent Nested table as variable/Object in OCI

    Hi All,
    I'm new to OCI.
    I've following nested table in my database.
    Nested table:
    create type type1 as object (name varchar2(20));
    create type type2 as table of type1;
    create table table1 (col1 varchar2(20), col2 type2) nested table col2 store as table2;
    Can anyone help me to present col2 as C structure/typedef so as to use it with OCIDefineObject?

    You can have a look at Chapter 11 of the OCI Programmer's Guide. Look at the section Collections in it. You can represent the nested table as OCITable *. Further, you can generate structure representation of your object type by using OTT. Please let us know if this answers your question. In case you are not able to proceed please let us know.
    Thanks,
    Sumit

  • Update Nested Table Problem

    Hi All,
    I have a update problem in nested table.
    Below is my query:
    CREATE OR REPLACE TYPE TRACER.SEARCH_DATA AS TABLE OF VARCHAR2(20);
    UPDATE TRACER_SEARCH_SCHEDULE_LOT_NUM
    SET NOT_FOUND_SOR_LOT_NUM = SEARCH_DATA(
    SELECT
    COLUMN_VALUE
    FROM
    TABLE (SELECT SORTING_LOT_NUMBER FROM TRACER_SEARCH_SCHEDULE_LOT_NUM WHERE JOB_ID = 8)
    WHERE
    TRIM(COLUMN_VALUE) NOT IN (SELECT DISTINCT (SORTING_LOT_NUMBER) FROM SEARCH_SCHEDULE_RESULT_LOT_NUM WHERE JOB_ID = 8)
    ) WHERE JOB_ID = 8;
    ORA-00936: missing expression
    or I try as following
    DECLARE
    sor_lot_num_not_found SEARCH_DATA :=
    SEARCH_DATA
    SELECT
    FROM
    TABLE (SELECT SORTING_LOT_NUMBER FROM TRACER_SEARCH_SCHEDULE_LOT_NUM WHERE JOB_ID = 8)
    WHERE
    TRIM(COLUMN_VALUE) NOT IN (SELECT DISTINCT (SORTING_LOT_NUMBER) FROM SEARCH_SCHEDULE_RESULT_LOT_NUM WHERE JOB_ID = 8)
    BEGIN
    UPDATE TRACER_SEARCH_SCHEDULE_LOT_NUM SET NOT_FOUND_SOR_LOT_NUM = sor_lot_num_not_found WHERE JOB_ID = 8;
    END;
    ORA-06550: line 5, column 9:
    PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
    ( ) - + case mod new not null others <an identifier>
    table avg count current exists max min prior sql stddev sum
    variance execute multiset the both leading trailing forall
    merge year month DAY_ hour minute second timezone_hour
    timezone_minute timezone_region timezone_abbr time timestamp
    interval date
    <a string literal with character set specificat
    ORA-06550: line 11, column 5:
    PLS-00103: Encountered the symbol ")" when expecting one of the following:
    ; for and or group having intersect minus order start union
    where connect
    ORA-06550: line 14, column 4:
    PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
    begin case declare end exception exit for goto if loop mod
    null pragma raise return select update while with
    <an identifier> <a double-quoted d
    I have try on the Select Statement, it work. So is it the way that I assign data from nested table and update method is wrong?
    Edited by: skymonster84 on Mar 8, 2011 5:12 PM

    Hi,
    I think MULTISET operators might interest you.
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/operators006.htm
    Not tested :
    UPDATE tracer_search_schedule_lot_num
    SET not_found_sor_lot_num =
          sorting_lot_number
          MULTISET EXCEPT ALL
          CAST(
            MULTISET(
              SELECT distinct sorting_lot_number
              FROM search_schedule_result_lot_num
              WHERE job_id = 8
            AS search_data
    WHERE job_id = 8
    ;

  • About nested tables in oracle 8i

    hello,
    actually i am working with oracle 8.1.5 's nested tables
    concept...
    here is a description of my tables
    create type parameterranges
    parameter_name varchar2(20),
    min_value number(10),
    max_value number(10)
    create type parameter_ran as table of parameterranges
    create table material_details
    mat_type varchar2(20),
    parameter_ranges parameter_ran
    okay...
    now my doubt is how do i place constraints on the nested table fields i.e on min_value etc...(especially NOT NULL
    constraint)
    DOUBT NO 2
    =============
    I have a query to find out the mat_type,partno from material_details table Based on the parameter value and its min_value ,i.e based on some name value pairs which I am achieving as below .
    select m.mat_type,m.partno
    from material_details m,table(m.parameter_ranges) p
    where p.parameter ='THICKNESS' and p.min_value = '1'
    and m.mat_type='STEEL'
    intersect
    select m.mat_type, m.partno
    from material_details m,table(m.parameter_ranges) p
    where p.parameter ='STANDARD' and p.min_value = 'SAE1010'
    and m.mat_type='STEEL';
    Now I want this to be in a cursor..i.e I want to use the same set of rows returned by the above in another query involving another table .
    That is using the multiple mat_type and partno returned from above I want to find out
    Other fields (company,plant) from another table part_details which also has a nested table in it
    How do I go about this???Actually I want to use these in a PLSQL procedure where we can have row by row control of the rows returned ,that is why I want a cursor.......
    could u think about this too...and if possible mail me at my yahoo id ..
    thanx once again
    please reply to my id
    [email protected]
    thanx
    null

    I don't understand exactly your problem. Can you send me a mail which expresses your problem??

  • IN operator in nested tables

    Hi,
    Does anyone can redo an IN operator in nested tables example?
    http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28371/adobjcol.htm#sthref396
    My example returns no row...
    CREATE TYPE Pilote_elt_nt_type AS OBJECT
    (brevet VARCHAR(4), nomPil VARCHAR(15),
    MAP MEMBER FUNCTION get_brevet RETURN VARCHAR)
    CREATE TYPE BODY Pilote_elt_nt_type AS
    MAP MEMBER FUNCTION get_brevet RETURN VARCHAR IS
    BEGIN
    RETURN brevet;
    END get_brevet ;
    END;
    CREATE TYPE Pilotes_nt_type AS TABLE OF Pilote_elt_nt_type
    CREATE TABLE Compagnie
    (numComp VARCHAR2(2) PRIMARY KEY,
    nomComp VARCHAR2(20),
    commandants_nt Pilotes_nt_type,
    instructeurs_nt Pilotes_nt_type,
    pilotes_nt Pilotes_nt_type)
    NESTED TABLE commandants_nt STORE AS commandants_tabnt
    NESTED TABLE instructeurs_nt STORE AS instructeurs_tabnt
    NESTED TABLE pilotes_nt STORE AS pilotes_tabnt;
    INSERT INTO Compagnie
    VALUES ('C1','Air France',
    Pilotes_nt_type (
              Pilote_elt_nt_type ('PL-1','C. Sigaudes'),
    Pilote_elt_nt_type ('PL-3','A. Bidal'),
    Pilote_elt_nt_type ('PL-2','S. Payrissat')
    Pilotes_nt_type (
              Pilote_elt_nt_type ('PL-2','S. Payrissat')
    Pilotes_nt_type (          
    Pilote_elt_nt_type ('PL-3','A. Bidal'),
    Pilote_elt_nt_type ('PL-1','C. Sigaudes'),
              Pilote_elt_nt_type ('PL-4','F. Périssel')) );
    SELECT p.nomPil
    FROM Compagnie, TABLE(commandants_nt) p;
    SELECT p.nomPil
    FROM Compagnie, TABLE(instructeurs_nt) p;
    SELECT p.nomPil
    FROM Compagnie, TABLE(pilotes_nt ) p;
    --no row !
    SELECT p.nomPil
    FROM Compagnie, TABLE(commandants_nt) p
    WHERE commandants_nt IN (pilotes_nt,instructeurs_nt);

    Actually, my general advices are not my original advices, but (mostly) C.J.Date's advices.
    I'm IT practitioner (not IT scientists), but I highly appreciate work (theoretical and practical) of IT scientists like
    Edsger W.Dijkstra, C.Antony.R Hoare, John W.Backus, Peter Naur, Ole-Johan Dahl, Kristen Nygaard, Donald E.Knuth,
    Niklaus E.Wirth, Alan C.Kay, Edgar F.Codd, Christopher J.Date, Bertrand Meyer ... and many more.
    I like OOPL's, especially Eiffel. But mostly I like relational model and relational DBMS's.
    My motto is: “Thou shall not do in the Middle Tier, what thou could have done in the Data Tier”
    (Toon Koppelaars in "A first JDeveloper project: Choices made, lessons learned", Oracle World 2002).
    First, I don't like to use REF's in Oracle (relational) DBMS.
    C.J.Date in "An introduction to Database Systems" (eighth edition, 2004, chapter 26) says:
    - "The Second Great Blunder consists of mixing pointers [REF's] and relations"
    - "The Second Great Blunder undermines the conceptual integrity of the relational model in numerous ways"
    Second, using nested tables in relational database is "legal". In the same book (page 373) Date says:
    "... it is possible for a relation to include an attribute whose values are relations in turn...
    Historically, in fact, such relvars [relation variables] were not even legal -
    they were said to be unnormalized, meaning they were not even regarded as being in 1NF".
    But, note that on the same page Date says:
    "From the point of view of database design, however, such relvars are usually contraindicated,
    because they tend to be asymmetric ... and such asymmetry can lead to various practical problems".
    So, we can use nested tables (relational-valued attributes), but very very sparingly, and I agree with Billy (Verreynne):
    I also think this design of yours (using nested tables instead of normal relational tables) it a very much flawed approach. Third, I use object types as domains. In the same book (page 885) Date says:
    "... object/relational systems ... are, or should be, basically just relational systems that support the relational domain concept (i.e., types) properly
    - in other words, true relational systems, meaning in particular systems that allow users to define their own types".
    Here is my attempt to use Oracle "object-relational" features "in the proper way" (in Date's sense) - to use object type as domain:
    “OR(DBMS) or R(DBMS), That is the Question”
    http://www.quest-pipelines.com/pipelines/plsql/tips.htm#OCTOBER
    Date says that "The First Great Blunder" is to equate object classes and relational variables,
    simply speaking - to have object tables (tables in which each row represents an object).
    I must say that I'm not 100% sure about "The First Great Blunder" in Oracle (see Re: to REF or not to REF? or Re: difference between value and deref clause in oop).
    Date says that one consequence of "The First Great Blunder" is to have subtables and supertables.
    Subtables and supertables exists in SQL:1999 standard. But, in Oracle we can't say (SQL:1999 syntax):
    CREATE TABLE programmer_obj_tab OF programmer_type UNDER emp_obj_tab;
    Oracle hasn't (explicit) subtables and supertables.
    I recommend to you Billy's threads - you can find many excellent advices and opinions.
    Regards,
    Zlatko

  • Open sys_refcursor for select from table variable?

    Hi,
    I've got a challenge for you! :-)
    I've got a procedure that has a lot of logic to determine what data should be loaded into a table variable. Because of various application constraints, i can not create a global temporary table. Instead, i'd like to create a table variable and populate it with stuff as i go through the procedure.
    The end result of the procedure is that i must be able to pass the results back as a sys_refcursor. This is a requirement that is beyond my control as well.
    Is there a way to make this sort of procedure work?
    Create Or Replace Procedure Xtst
    Mu_Cur In Out Sys_Refcursor
    Is
    Type Xdmlrectype Is Record (Col1 Varchar2(66));
    Type Xdmltype Is Table Of Xdmlrectype;
    Rtn Xdmltype;
    Begin
    Select Internal_Id Bulk Collect Into Rtn From Zc_State;
    open mu_cur for select col1 from table(rtn);
    end;
    11/42 PLS-00642: local collection types not allowed in SQL statements
    11/36 PL/SQL: ORA-22905: cannot access rows from a non-nested table item
    11/19 PL/SQL: SQL Statement ignored
    Show Errors;

    Not anything i'd want to personally implement.
    But for educational purposes only of course....
    create table this_will_be_gross
       column1 number,
       column2 varchar2(30)
    insert into this_will_be_gross values (1, 'begin the ugliness');
    insert into this_will_be_gross values (2, 'end the ugliness');
    variable x refcursor;
    ME_XE?
    declare
       Rtn sys.ODCIVARCHAR2LIST;
    BEGIN
       SELECT
          column1 || '-' || column2 Bulk Collect
       INTO
          Rtn
       FROM
          this_will_be_gross;
       OPEN :x FOR
       SELECT 
          regexp_substr (column_value, '[^-]+', 1, 1) as column1,
          regexp_substr (column_value, '[^-]+', 1, 2) as column2      
       FROM TABLE(CAST(rtn AS sys.ODCIVARCHAR2LIST));
    end;
    17  /
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.09
    ME_XE?
    ME_XE?print :x
    COLUMN1                        COLUMN2
    1                              begin the ugliness
    2                              end the ugliness
    2 rows selected.
    Elapsed: 00:00:00.11In the above example i 'knew' that a hypen was a safe character to use to break up my data elements (as it would not be found anywhere in the data itself).
    I would strongly encourage you not to implement something like this. I realize it's tempting when you are working in strict environments where it can take a serious battle to get structures like temporary tables or SQL Types created, but that's really the proper approach to be taking.

  • Nested Table: How to display formatted text in the form ?

    Hi,
    Scenario:
    I have a nested table, say TAB1, containing another table TAB2 which holds the formatted text.
    Sample data
    Entries in TAB1:
    Column1       Column2(TAB2)
    Text1         Data_from_tab2
    Text2         Data_from_tab2
    Text3         Data_from_tab2
    Requirement:
    The requirement is to display the data in TAB1 as it is maintained.
    Trials:
    I am aware of the fact that we can transfer the content of the nested table (in this scenario, TAB2) in another table(of type TLINE) defined as a global variable in the interface of the form. Then in the context area, we can define a 'TEXT' node and bind it to the table and choose the 'Dynamic text' for the 'text type' attribute and maintain the other atrributes.
    But this approach cannot solve the issue as it is a nested table.
    Kindly suggest how can I resolve this issue.
    Regards
    s@k

    Hi,
    if its like colum1, column2 (tab2).
    you can represent column2 as a nested table in the form. and put these tables structure intoa subform of type flowed.
    then you can have the required format.
    the same can also be acheived using nested subforms instead of tables.
    example of such scenario is PO & line items.
    po number1 , items 1
                          item 2
                          item 3
    po number2 , items 1
                          item 2
                          item 3
    hope this helps you.
    Cheers,
    Sai

  • When selecting a row from a view with a nested table I want just ONE entry returned

    Does a nested table in a view "EXPLODE" all values ALWAYS no matter the where clause for the nested table?
    I want to select ONE row from a view that has columns defined as TYPE which are PL/SQL TABLES OF other tables.
    when I specify a WHERE clause for my query it gives me the column "EXPLODED" with the values that mathc my WHERE clause at the end of the select.
    I dont want the "EXPLODED" nested table to show just the entry that matches my WHERE clause. Here is some more info:
    My select statement:
    SQL> select * from si_a31_per_vw v, TABLE(v.current_allergies) a where a.alg_seq
    =75;
    AAAHQPAAMAAAAfxAAA N00000 771 223774444 20 GREGG
    CADILLAC 12-MAY-69 M R3
    NON DENOMINATIONAL N STAFF USMC N
    U
    E06 11-JUN-02 H N
    05-JAN-00 Y Y
    USS SPAWAR
    353535 USS SPAWAR
    SI_ADDRESS_TYPE(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NUL
    L, NULL)
    SI_ADDRESS_TAB()
    SI_ALLERGY_TAB(SI_ALLERGY_TYPE(69, 'PENICILLIN', '11-JUN-02', NULL), SI_ALLERGY
    TYPE(74, 'SHELLFISH', '12-JUN-02', NULL), SIALLERGY_TYPE(68, 'PEANUTS', '13-J
    UN-02', NULL), SI_ALLERGY_TYPE(75, 'STRAWBERRIES', '13-JUN-02', NULL))
    SI_ALLERGY_TAB()
    75 STRAWBERRIES 13-JUN-02
    *******Notice the allergy entry of 75, Strawberries, 13-JUN-02 at the
    end. This is what I want not all the other exploded data.
    SQL> desc si_a31_per_vw
    Name Null? Type
    ........ Omitted uneeded previous column desc because of metalink
    character limit but the view is bigger then this.......
    DEPT_NAME VARCHAR2(20)
    DIV_NAME VARCHAR2(20)
    ADDRESSES SI_ADDRESS_TAB
    CURRENT_ALLERGIES SI_ALLERGY_TAB
    DELETED_ALLERGIES SI_ALLERGY_TAB
    SQL> desc si_allergy_tab
    si_allergy_tab TABLE OF SI_ALLERGY_TYPE
    Name Null? Type
    ALG_SEQ NUMBER
    ALG_NAME VARCHAR2(50)
    START_DATE DATE
    STOP_DATE DATE
    SQL> desc si_allergy_type
    Name Null? Type
    ALG_SEQ NUMBER
    ALG_NAME VARCHAR2(50)
    START_DATE DATE
    STOP_DATE DATE

    Can you explain what do you mean by the following?
    "PL/SQL tables (a.k.a. Index-by tables) cannot be used as the basis for columns and/or attributes"There are three kinds of collections:
    (NTB) Nested Tables
    (VAR) Varrying Arrays
    (IBT) Index-by Tables (the collection formerly known as "PL/SQL tables")
    NTB (and VAR) can be defined as persistent user defined data types, and can be used in table DDL (columns) and other user defined type specifications (attributes).
    SQL> CREATE TYPE my_ntb AS TABLE OF INTEGER;
    SQL> CREATE TABLE my_table ( id INTEGER PRIMARY KEY, ints my_ntb );
    SQL> CREATE TYPE my_object AS OBJECT ( id INTEGER, ints my_ntb );
    /IBT are declared inside stored procedures only and have slightly different syntax from NTB. Only variables in stored procedures can be based on IBT declarations.
    CREATE PROCEDURE my_proc IS
       TYPE my_ibt IS TABLE OF INTEGER INDEX BY BINARY_INTEGER;  -- now you see why they are called Index-by Tables
       my_ibt_var my_ibt;
    BEGIN
       NULL;
    END;That sums up the significant differences as it relates to how they are declared and where they can be referenced.
    How are they the same?
    NTB and VAR can also be (non-persistently) declared in stored procedures like IBTs.
    Why would you then ever use IBTs?
    IBTs are significantly easier to work with, since you don't have to instantiate or extend them as you do with NTB and VAR, or
    Many other highly valuable PL/SQL programs make use of them, so you have to keep your code integrated/consistent.
    There's a lot more to be said, but I think this answers the question posed by Sri.
    Michael

  • Using FOR .. LOOP counter in handling of PL/SQL procedures with nest. table

    Hi all!
    I'm learning PL/SQL on Steve Bobrovsky's book (specified below sample is from it) and I've a question.
    In the procedure of specified below program used an integer variable currentElement to get reference to the row of nested table of %ROWTYPE datatype.
    Meanwhile, the program itself uses a common FOR .. LOOP counter i.
    DECLARE
    TYPE partsTable IS TABLE OF parts%ROWTYPE;
    tempParts partsTable := partsTable();
    CURSOR selectedParts IS
      SELECT * FROM parts ORDER BY id;
    currentPart selectedParts%ROWTYPE;
    currentElement INTEGER;
    PROCEDURE printParts(p_title IN VARCHAR2, p_collection IN partsTable) IS
      BEGIN
       DBMS_OUTPUT.PUT_LINE(' ');
       DBMS_OUTPUT.PUT_LINE(p_title || ' elements: ' || p_collection.COUNT);
       currentElement := p_collection.FIRST;
       FOR i IN 1 .. p_collection.COUNT
       LOOP
        DBMS_OUTPUT.PUT('Element #' || currentElement || ' is ');
         IF tempParts(currentElement).id IS NULL THEN DBMS_OUTPUT.PUT_LINE('an empty element.');
         ELSE DBMS_OUTPUT.PUT_LINE('ID: ' || tempParts(currentElement).id || ' DESCRIPTION: ' || tempParts(currentElement).description);
         END IF;
        currentElement := p_collection.NEXT(currentElement);
       END LOOP;
    END printParts;
    BEGIN
    FOR currentPart IN selectedParts
    LOOP
      tempParts.EXTEND(2);
      tempParts(tempParts.LAST) := currentPart;
    END LOOP;
    printParts('Densely populated', tempParts);
    FOR i IN 1 .. tempParts.COUNT
    LOOP
      IF tempParts(i).id is NULL THEN tempParts.DELETE(i);
      END IF;
    END LOOP;
    FOR i IN 1 .. 50
    LOOP
      DBMS_OUTPUT.PUT('-');
    END LOOP;
    printParts('Sparsely populated', tempParts);
    END;
    /When I've substituted an INTEGER global variable with such FOR .. LOOP counter, an APEX have returned an error "ORA-01403: no data found".
    DECLARE
    TYPE partsTable IS TABLE OF parts%ROWTYPE;
    tempParts partsTable := partsTable();
    CURSOR selectedParts IS
      SELECT * FROM parts ORDER BY id;
    currentPart selectedParts%ROWTYPE;
    PROCEDURE printParts(p_title IN VARCHAR2, p_collection IN partsTable) IS
      BEGIN
       DBMS_OUTPUT.PUT_LINE(' ');
       DBMS_OUTPUT.PUT_LINE(p_title || ' elements: ' || p_collection.COUNT);
       FOR i IN 1 .. p_collection.COUNT
       LOOP
        DBMS_OUTPUT.PUT('Element is ');
         IF tempParts(i).id IS NULL THEN DBMS_OUTPUT.PUT_LINE('an empty element.');
         ELSE DBMS_OUTPUT.PUT_LINE('ID: ' || tempParts(i).id || ' DESCRIPTION: ' || tempParts(i).description);
         END IF;
       END LOOP;
    END printParts;
    BEGIN
    FOR currentPart IN selectedParts
    LOOP
      tempParts.EXTEND(2);
      tempParts(tempParts.LAST) := currentPart;
    END LOOP;
    printParts('Densely populated', tempParts);
    FOR i IN 1 .. tempParts.COUNT
    LOOP
      IF tempParts(i).id is NULL THEN tempParts.DELETE(i);
      END IF;
    END LOOP;
    FOR i IN 1 .. 50
    LOOP
      DBMS_OUTPUT.PUT('-');
    END LOOP;
    printParts('Sparsely populated', tempParts);
    END;
    /When I've tried to handle this code in SQL*Plus, the following picture have appeared:
    Densely populated elements: 10
    Element is an empty element.
    Element is ID: 1 DESCRIPTION: Fax Machine
    Element is an empty element.
    Element is ID: 2 DESCRIPTION: Copy Machine
    Element is an empty element.
    Element is ID: 3 DESCRIPTION: Laptop PC
    Element is an empty element.
    Element is ID: 4 DESCRIPTION: Desktop PC
    Element is an empty element.
    Element is ID: 5 DESCRIPTION: Scanner
    Sparsely populated elements: 5
    DECLARE
    ERROR at line 1:                                 
    ORA-01403: no data found                         
    ORA-06512: at line 14                            
    ORA-06512: at line 35What's wrong in code(or what I have not understood)? Help please!

    942736 wrote:
    What's wrong in code(or what I have not understood)? Help please!First code. You have collection of 10 elements:
    1 - null
    2 - populated
    3 - null
    4 - populated
    5 - null
    6 - populated
    7 - null
    8 - populated
    9 - null
    10 - populated
    Then you delete null elements and have 5 element collection
    2 - populated
    4 - populated
    6 - populated
    8 - populated
    10 - populated
    Now you execute:
    printParts('Sparsely populated', tempParts);Inside procedure you execute:
    currentElement := p_collection.FIRST;
    This assingns currentElement value 2. Then procedure loops 5 times (collection element count is 5). Element 2 exists. Inside loop procedure executes:
    currentElement := p_collection.NEXT(currentElement);
    which assigns currentElement values 4,6,8,10 - all existing elements.
    Now second code. Everything is OK until you delete null elements. Again we have:
    2 - populated
    4 - populated
    6 - populated
    8 - populated
    10 - populated
    Again you execute:
    printParts('Sparsely populated', tempParts);Now procedure loops 5 times (i values are 1,2,3,4,5):
    FOR i IN 1 .. p_collection.COUNT
    Very first iteration assingns i value 1. And since collection has no element with substript 1 procedure raises no data found.
    SY.

  • Issue with Mulidimensional Nested Table

    Hi All,
    I am studing Multidimensional Nested table and have the below code:
    DECLARE
      TYPE table_type1 IS TABLE OF INTEGER;
      TYPE table_type2 IS TABLE OF TABLE_TYPE1;
      table_tab1 table_type1 := table_type1();
      table_tab2 table_type2 := table_type2(table_tab1);
    BEGIN
      FOR i IN 1 .. 2
      LOOP
        table_tab2.extend;
        table_tab2(i) := table_type1();
        FOR j IN 1 .. 3
        LOOP
          IF i = 1
          THEN
            table_tab1.extend;
            table_tab1(j) := j;
          ELSE
            table_tab1.extend;
            table_tab1(j) := 4 - j;
          END IF;
            table_tab2.extend;
          table_tab2(i)(j) := table_tab1(j);
          DBMS_OUTPUT.PUT_LINE('table_tab2(' || i || ')(' || j || '): ' ||
                               table_tab2(i) (j));
        END LOOP;
      END LOOP;
    exception
      when others then
        dbms_output.put_line(sqlerrm);
    END;
    This code is working fine as of now.But,If i comment below code(table_tab2 is also extended latter):
    table_tab2.extend; 
        table_tab2(i) := table_type1();
    then it gives me error 'Subscription Beyond count'.
    I would like to know why i need to extend table_tab2 twice?
    Thanks!

    This code is working fine as of now
    No, it isn't. Make sure you have serveroutput on. If you do, you get this as script output (I am using SQL Developer):
    anonymous block completed
    ...meaning no exception was raised to client, because you trapped it, but the DBMS Output window gives:
    ORA-06533: Subscript beyond count
    ...with no indication of which line, because you suppressed it (why?). If you drop the worse than useless exception handler, you get:
    ORA-06533: Subscript beyond count
    ORA-06512: at line 22
    06533. 00000 -  "Subscript beyond count"
    *Cause:    An in-limit subscript was greater than the count of a varray
               or too large for a nested table.
    *Action:   Check the program logic and explicitly extend if necessary.
    A bit more helpful, yes? and with less code. Here is a revised block that writes the loop variable product to the nested array, with its output, initialising and extending correctly:
    DECLARE
      TYPE table_type1 IS   TABLE OF INTEGER;
      TYPE table_type2 IS   TABLE OF table_type1;
      table_tab1            table_type1;
      table_tab2            table_type2 := table_type2();
    BEGIN
      FOR i IN 1..2 LOOP
        table_tab1 := table_type1();
        FOR j IN 1..3 LOOP
          table_tab1.extend;
          table_tab1(j) := i * j;
        END LOOP;
        table_tab2.extend;
        table_tab2(i) := table_tab1;
      END LOOP;
      FOR i IN 1..table_tab2.COUNT LOOP
        FOR j IN 1..table_tab2(i).COUNT LOOP
          DBMS_OUTPUT.PUT_LINE('Row ' || i || ' element ' || j || ' = ' || table_tab2(i)(j));
        END LOOP;
      END LOOP;
    END;
    Row 1 element 1 = 1
    Row 1 element 2 = 2
    Row 1 element 3 = 3
    Row 2 element 1 = 2
    Row 2 element 2 = 4
    Row 2 element 3 = 6
    You could alternatively dispense with table_tab1 if you prefer, and write directly each element.

  • Nested tables questions

    I ve been using nested tables ( with the 'index by' clause ).
    I understand that the created array is stored in the RAM memory ( and not in the database files ).
    1. Does this mean that my program might not run one day when the machine is running low on RAM ?
    2. If yes, will there be an exception or something ?
    3. I understand that the memory is freed when the 'session ends'. When does my session end ? ( Is it when my PROCEDURE/function ends or is it when I quit sqlplus )
    4. Are nested tables/collections thread safe ?
    If I declare a nested table within the procedure, and if the procedure is called simultaneously by two clients, will there be a problem ?
    Thanks

    1. Yes
    2. Yes, possibly "PLS-00996: out of memory" although there may be others
    3. PL/SQL does garbage collection at various times, including when your session ends (i.e. when you disconnect from Oracle) and when a variable goes out of scope (e.g. when a procedure ends). I don't think the full list of rules is documented.
    4. Yes, although I'm not sure what happens in connection pooling.

  • Varray, Nested Table and Object types in OWB r2

    Requirement:
    Flat file with repeating groups of nested content need to move into Object Relational ORACLE table (using varray or nested tables - no preference). The data will be loaded, then mapped/transformed into a richer O-R output to directly produce XML outputs.
    Problem:
    Generated PL/SQL "seems" to do the correct thing, but deployment errors show failures on mapping of collections (varrays, NTs or OTs) and in sqlplus recompiling the PKB still gives the errors. Is this a PL/SQL generator error, or is there a more meaningful example of using CONSTRUCT OBJECT operator than the embedded odcumentation - it is a simple type (single instance) and not a variable repeating group of nested data.
    Anyone had any success with these, or know of any collateral to assist in the process. Thanks.

    The process we are following is very simple. We are talking 10 columns from a source flat file table and wish to map this into a Varray/Nested table, with one column of Varchar2(10).
    When you create your map in OWB, select the construct object, you have to choose an object type - it does not allow you to select a VARAAY or NESTED table.
    I have then created an object defined in the same structure as the VARRAY/NESTED table - I have then made the VARRAY/NESTED table of this TYPE.
    Example:
    CREATE OR REPLACE TYPE "O_REL_PUB_INDEX" AS OBJECT (
    X_REL_PUB_INDEX_1 VARCHAR2(10))
    CREATE OR REPLACE TYPE "V_REL_PUB_INDEX" AS VARRAY(15) OF O_REL_PUB_INDEX
    In OWB you can then select O_REL_PUB_INDEX when creating the 'Contruct Object'.
    The problem I have is that when I map to my target column of type V_REL_PUB_INDEX and DEPLOY my map I get the following errors taken from OWB control centre
    Name
    Action
    Status
    Log
    TEST
    Create
    Warning
    ORA-06550: line 2931, column 9:
    PL/SQL: SQL Statement ignored
    TEST
    Create
    Warning
    ORA-06550: line 3174, column 11:
    PL/SQL: ORA-00932: inconsistent datatypes: expected OWB_USER.O_REL_PUB_INDEX got OWB_USER.V_REL_PUB_INDEX
    TEST
    Create
    Warning
    ORA-06550: line 401, column 7:
    PL/SQL: SQL Statement ignored
    TEST
    Create
    Warning
    ORA-06550: line 643, column 13:
    PL/SQL: ORA-00932: inconsistent datatypes: expected OWB_USER.O_REL_PUB_INDEX got OWB_USER.V_REL_PUB_INDEX
    TEST
    Create
    Warning
    ORA-06550: line 7221, column 9:
    PL/SQL: SQL Statement ignored
    TEST
    Create
    Warning
    ORA-06550: line 7464, column 11:
    PL/SQL: ORA-00932: inconsistent datatypes: expected OWB_USER.O_REL_PUB_INDEX got OWB_USER.V_REL_PUB_INDEX
    Any ideas? anyone succesfully mapped to either a VARRAY or an NESTED TABLE target column?

  • Open cursor for a nested table

    Hi,
    I want to open a cursor like:
    open c1 for select * from emp;
    BUT
    I what the cursor results to be populated with contents of a nested table or associative array..
    How can this be done???
    Thanks in advance,
    teo

    Well, given a variable YOUR_EMP of nested table type EMP_NT it could be as simple as
    open c1 for select * from TABLE( CAST(your_emp AS emp_nt));Cheers, APC

  • Oracle equivalent to SQL Server Table Variables ?

    Does Oracle have anything equivalent to SQL Server table variables, that can be used in the JOIN clause of a select statement ?
    What I want to do is execute a query to retrieve a two-column result, into some form of temporary storage (a collection ?), and then re-use that common data in many other queries inside a PL/SQL block. I could use temporary tables, but I'd like to avoid having to create new tables in the database, if possible. If I was doing this in SQL Server, I could use a table variable to do this, but is there anything similar in Oracle ? SQL Server example:
    use Northwind
    DECLARE @myVar TABLE(CustomerID nchar(5), CompanyName nvarchar(40))
    INSERT INTO @myVar(CustomerID, CompanyName)
    select CustomerID, CompanyName
    from Customers
    --Join the variable onto a table in the database
    SELECT *
    FROM @myVar mv join Customers
    on mv.CompanyName = Customers.CompanyName
    The closest I've found in Oracle is to use CREATE TYPE to create new types in the database, and use TABLE and CAST to convert the collection to a table, as shown below. I can't see anyway without creating new types in the database.
    CREATE TYPE IDMap_obj AS Object(OldID number(15), NewID number(15));
    CREATE TYPE IDMap_TAB IS TABLE OF IDMap_obj;
    DECLARE
    v_Count Number(10) := 0;
    --Initialize empty collection
    SourceIDMap IDMap_TAB := IDMap_TAB();
    BEGIN
    --Populate our SourceIDMap variable (dummy select statement for now).
    FOR cur_row IN (select ID As OldID, ID + 10000000 As NewID From SomeTable) LOOP
    SourceIDMap.extend;
    SourceIDMap(SourceIDMap.Last) := IDMap_obj(cur_row.OldId, cur_row.NewId);
    END LOOP;
    --Print out contents of collection
    FOR cur_row IN 1 .. SourceIDMap.Count LOOP
    DBMS_OUTPUT.put_line(SourceIDMap(cur_row).OldId || ' ' || SourceIDMap(cur_row).NewId);
    END LOOP;
    --OK, can we now use our collection in a JOIN statement ?
    SELECT COUNT(SM.NewID)
    INTO v_Count
    FROM SomeTable ST JOIN
    TABLE(CAST(SourceIDMap As IDMap_TAB)) SM
    ON ST.ID = SM.OldID;
    DBMS_OUTPUT.put_line(' ' );
    DBMS_OUTPUT.put_line('v_Count is ' || v_Count);
    END;

    Hi, got this from our plsql guys:
    The term "table function" is a bit confusing here. In Oracle-speak, it means a function that can be used in the from list of a select statement thus:
    select * from Table(My_Table_Function()),..
    where...
    The function's return type must be a collection that SQL understands. So for the interesting case -- mimicking a function with more than one column -- this would be a nested table of ADTs where both the ADT and the nested table are defined at schema level. PL/SQL -- by virtue of some clever footwork -- allows you to declare the type as a nested table of records where both these types are declared in a package spec. This alternative is generally preferred, especially because the nested table can be of Some_Table%rowtype (or Some_Cursor%rowtype if you prefer).
    As I understand it from our man on the ANSI committee, our use terminology follows the standard.
    The construct below seems to be a bit different (though there are similarities) because it appears from your code sample that it's usable only within procedural code. And the object from which you select is a variable rather than a function.
    So, after that preamble... the answer would be:
    No, we don't have any constructs to let you "declare" something that looks like a regular schema-level table as a PL/SQL variable -- and then use (static) SQL on it just as if it were a schema-level table.
    But yes, you can use PL/SQL's pipelined table function to achieve much of the same effect.
    Look at the attached Table_Function.sql.
    It shows that you can populate a collection of records using ordinary PL/SQL code. You can't use SQL for insert, update, or delete on such a collection. I see that SQL Server lets you do
    insert into Program_Variable_Table select... from Schema_Level_Table
    The PL/SQL equivalent would be
    select...
    bulk collect into Program_Variable_Collection
    from Schema_Level_Table
    The attached shows that once you have populated your collection, then you can then query it with regular SQL -- both from inside PL/SQL code and from naked SQL.
    and the code is here
    CONNECT System/p
    -- Drop and re-create "ordinary" user Usr
    EXECUTE d.u
    CONNECT Usr/p
    create table Schema_Things(ID number, Description Varchar2(80))
    create package Pkg is
    subtype Thing_t is Schema_Things%rowtype;
    type Things_t is table of Thing_t; -- index by pls_integer
    Things Things_t;
    -- PLS-00630: pipelined functions must have
    -- a supported collection return type
    -- for "type Things_t is table of Thing_t index by pls_integer".
    function Computed_Things return Things_t pipelined;
    procedure Insert_Schema_Things(No_Of_Rows in pls_integer);
    end Pkg;
    create package body Pkg is
    function Computed_Things return Things_t pipelined is
    Idx pls_integer;
    Thing Thing_t;
    begin
    Idx := Things.First();
    while Idx is not null loop
    pipe row (Things(Idx));
    Idx := Things.Next(Idx);
    end loop;
    end Computed_Things;
    procedure Insert_Schema_Things(No_Of_Rows in pls_integer) is
    begin
    Things := Things_t();
    Things.Extend(No_Of_Rows);
    for j in 1..No_Of_Rows loop
    Things(j).ID := j;
    Things(j).Description := To_Char(j, '00009');
    end loop;
    insert into Schema_Things
    select * from Table(Pkg.Computed_Things());
    end Insert_Schema_Things;
    end Pkg;
    -- Test 1.
    begin Pkg.Insert_Schema_Things(100); end;
    select * from Schema_Things
    -- Test 2.
    begin
    Pkg.Things := Pkg.Things_t();
    Pkg.Things.Extend(20);
    for j in 1..20 loop
    Pkg.Things(j).ID := j;
    Pkg.Things(j).Description := To_Char(j, '00009');
    end loop;
    for j in 1..5 loop
    Pkg.Things.Delete(5 +2*j);
    end loop;
    end;
    select * from Table(Pkg.Computed_Things())
    /

Maybe you are looking for

  • I'm really frustrated with iTunes!! Please help

    iTunes has been prompting me to download the new version for months, but after what happened to me the last time I was very wary of upgrading (see http://forum.digitalspy.co.uk/board...ad.php?t=241985 ) Today I decided it was probably just an unfortu

  • Help! Utter chaos in brush preset pop-out

    ::scream!:: First of all - I'm neither familiar with nor do I utilize the technical terms for any of this junk (no offense intended. I know some of y'all are uber-serious about this..stuff...). I'm just the sort of person who calls things do-dads and

  • ITunes does not "populate" in ilife

    When I attempt to create a slideshow with music in iphoto, my itunes music does not show up in the "music" area.  itunes is open, and I have created a playlist specific to this slideshow.  I can chose the themes and the settings, but the itunes windo

  • Trouble with MergeFormat tags appearing in Word doc

    Hello! I have been living with this problem for ages, and just manually deleting them. But, I now have a new coworker who does not get the same problem when we single-source the same project to Word. When I create a single-source Word document, befor

  • IDVD unexpectedly quit

    I have tried numerous times to finish this DVD. I have done this many times before and never encountered these problems. It get throught the menu processing, the slideshow and menu processing, but when it gets through the audio, and just about to bur