Sys_refcursor vs collection parameter

When providing a result set as a function parameter, are there any advantages/disadvantages to using a sys_refcursor vs a user-defined collection type?

>
I was planning on iterating through the ref cursor and constructing a collection, then using table() to include it in the JOIN. Is that approach viable?
>
No - Justin already told you to use a pipelined function. The function can be treated as a table just like you want.
Try this samle code in the SCOTT schema.
-- type to match emp record
create or replace type emp_scalar_type as object
  (EMPNO NUMBER(4) ,
   ENAME VARCHAR2(10),
   JOB VARCHAR2(9),
   MGR NUMBER(4),
   HIREDATE DATE,
   SAL NUMBER(7, 2),
   COMM NUMBER(7, 2),
   DEPTNO NUMBER(2)
-- table of emp records
create or replace type emp_table_type as table of emp_scalar_type
-- pipelined function
create or replace function get_emp( p_deptno in number )
  return emp_table_type
  PIPELINED
  as
   TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE;
    emp_cv EmpCurTyp;
    l_rec  emp%rowtype;
  begin
    open emp_cv for select * from emp where deptno = p_deptno;
    loop
      fetch emp_cv into l_rec;
      exit when (emp_cv%notfound);
      pipe row( emp_scalar_type( l_rec.empno, LOWER(l_rec.ename),
          l_rec.job, l_rec.mgr, l_rec.hiredate, l_rec.sal, l_rec.comm, l_rec.deptno ) );
    end loop;
    return;
  end;
select * from table(get_emp(20))Now you can join that 'table' to the dept table
SQL> select * from dept where deptno in (select deptno from table(get_emp(20)));
    DEPTNO DNAME          LOC
        20 RESEARCH       DALLAS
SQL>Isn't that what you said you wanted to do?

Similar Messages

  • Problem w/ Collection Parameter in JDOQL

    I have created a collection of 2 strings "E2130" and "B6222"
    Here is the code for creating the query
    Collection nameSet = new HashSet();
    nameSet.add("E2130");
    nameSet.add("B6222");
    //firstNameSdex and lastNameSdex are members in the classType object
    String queryString = "nameSet.contains(firstNameSdex) ||
    nameSet.contains(lastNameSdex)";
    Query q = pm.newQuery(pm.getExtent(classType, true), queryString);
    q.declareImports("import java.util.Collection");
    q.declareParameters("Collection nameSet");
    Collection queryResults = (Collection) q.execute(nameSet);
    However queryResults always comes back w/ 0 results, I have verified that
    there are records in the DB w/ these string values, I am puzzled.
    Here is the JDO query
    executing statement <24669049>: (SELECT DISTINCT t0.FIRST_NAME,
    t0.FIRST_NAME_SDEX, t0.LAST_NAME, t0.LAST_NAME_SDEX, t0.MIDDLE_NAME,
    t0.MOTHER_MAIDEN_NAME FROM MPI.MPI_NAME t0 WHERE ((t0.FIRST_NAME_SDEX IN
    (?, ?) OR t0.LAST_NAME_SDEX IN (?, ?)))):
    [reused=1;params={(String)E2130,(String)B6222,(String)E2130,(String)B6222}]:
    null

    Abe White wrote:
    I just found the problem, it had nothing to do w/ jdo, when I was copying
    into a new collection to return back, I was using the copy constructor
    rather than doing an addall, so the query.close() was cleaning out my
    Collection i imagine. It works now
    executing statement <24669049>: (SELECT DISTINCT t0.FIRST_NAME,
    t0.FIRST_NAME_SDEX, t0.LAST_NAME, t0.LAST_NAME_SDEX, t0.MIDDLE_NAME,
    t0.MOTHER_MAIDEN_NAME FROM MPI.MPI_NAME t0 WHERE ((t0.FIRST_NAME_SDEX IN
    (?, ?) OR t0.LAST_NAME_SDEX IN (?, ?)))):
    The SQL looks fine to me. Have you tried executing this SQL exactly
    directly against the database (with the proper parameter values in place
    of the '?'s, of course) ?

  • Using CASE statement in Procedure,  SYS_REFCURSOR as OUT parameter

    Hi all,
    What is the mistake in this procedure
    create or replace procedure ConditionalSelect( param1 number, refCur IN OUT SYS_REFCURSOR ) is     
    begin
    case
    when param1 = 1 then open refCur for select * from AA;
    when param1 = 2 then open refCur for select * from EMPLOYEE;
         end;          
    end;
    The error i am getting is
    Error
    [row:1,col:1] ORA-24344: success with compilation error
    [row:8,col:5] PLS-00103: Encountered the symbol ";" when expecting one of the following:
    case
    The symbol "case" was substituted for ";" to continue.
    Thanks in advance
    pal

    a. you are missing an "end case;"
    b. in select - use case only with end - in pl/sql you shulde use "end case"
    like "end loop", "end if"
    c. case is much more easy to read then a bunch of if's and else if's and else.
    Amiel.

  • Collection as parameter

    Hey Kodo,
    I've tried using a Collection as parameter in order to obtain several
    Objects. The problem is, I've got duplicate results. Although this could be
    expected I'd like it better if I could somehow add a DISTINCT to the query.
    Here's my query:
    String filter = "secObjects.contains(priv.secObject) && priv.secGroup ==
    this";
    Query query = pm.newQuery(pm.getExtent(MirakelGroup.class,true),filter);
    query.declareImports("import com.madocke.util.security.jdo.*;import
    java.util.Collection;");
    query.declareParameters("Collection secObjects");
    query.declareVariables("JdoPrivilege priv");
    query.setOrdering("name ascending");
    Collection c = (Collection)query.execute(secObjects);
    What the query should do is return a number of MirakelGroups that somehow
    have privileges on one of the objects passed into the query.
    Thanks in advance,
    Martin van Dijken

    "Abe White" <[email protected]> wrote in message
    news:[email protected]..
    So am I correct in thinking that each MirakelGroup can have multiple
    JdoPrivilege instances associated with it? And you are getting a
    separate copy of each group back for each privilege that it has whose
    "secObject" is in the collection parameter?Quite correct, I'll clarify a little further:
    |SecObject |
    |Irrel. props|
    |JdoPrivilege |
    |SObj secObject |
    |MGroup group |
    |int rights |
    |MirakelGroup |
    |Irrel. props |
    secObject and group would be the keys if this were a straightforward db
    design. We're using Kodo identity, but that conveys the idea best.
    Now when I query for all Groups that have rights on one SecObject I simply
    get those returned. If I input a collection with two SecObjects who happen
    to have exactly the same combination of groups/rights I get every group
    twice. This pattern also applies to 3,4 etc.
    Martin van Dijken

  • SELECT from SYS_REFCURSOR?

    My function is being passed a SYS_REFCURSOR as a parameter. I need to use the values stored within it in one of my SELECT statements. If the REFCURSOR were a Collection I could do something along the lines of:
                 select *
                 from   my_table msg
                          table(cast(my_ref_cursor as my_obj_type)) v
                 where  msg.message_code = v.errorcodeHow can I acheive something similar with a REFCURSOR?
    I am currently using the LOOP/FETCH/EXIT/END LOOP construct to go through each record in the REFCURSOR and then using the ERRORCODE returned by each row in my SELECT statement however this seems a like a poor solution as the same SQL will be executed many times for each record in the REFCURSOR.
    Any ideas as to how I can turn the REFCURSOR into a Collection or a set of values that I can then use in my SELECT statement?

    You can if you go via XML. Consider:
    SQL> CREATE TYPE emp_typ AS OBJECT (
       empno      NUMBER (4),
       ename      VARCHAR (10),
       job        VARCHAR (9),
       mgr        NUMBER (4),
       hiredate   DATE,
       sal        NUMBER (7, 2),
       comm       NUMBER (7, 2),
       deptno     NUMBER (2)
    Type created
    SQL> CREATE TYPE emp_tab AS TABLE OF emp_typ
    Type created
    SQL> CREATE TYPE xmltype_tab AS TABLE OF XMLTYPE
    Type created
    SQL> CREATE OR REPLACE PROCEDURE p (cur IN sys_refcursor)
    AS
       emp_xml     XMLTYPE;
       p_emp_typ   emp_typ;
       mycur       sys_refcursor;
    BEGIN
    /*  Convert the cursor to XML */
       SELECT *
         INTO emp_xml
         FROM TABLE (CAST (XMLSEQUENCE (cur) AS xmltype_tab));
    /* Convert the XML to Object  */
       emp_xml.toobject (p_emp_typ);
    /*  Select from the corresponding Collection */
       OPEN mycur FOR
          SELECT *
            FROM TABLE (CAST (emp_tab (p_emp_typ) AS emp_tab));
       ---  DO_YOUR_STAFF_HERE
       CLOSE mycur;
    END p;
    Procedure created.
    SQL> DECLARE
       cur   sys_refcursor;
    BEGIN
       OPEN cur FOR
          SELECT *
            FROM emp
           WHERE empno = 7369;
    /*  Call procedure with REF cursor */
       p (cur);
       CLOSE cur;
    END;
    PL/SQL procedure successfully completed.Hope this helps.
    Regards
    Michael

  • SAP ME Data Collection setup

    Hello Experts!
    We are trying to set up data collection for following scenario:
    Typically our order quantity can vary from 1000 - 5000 pcs and we want to create only one SFC per shop order. We want to collect data after a fixed number of pcs are reported, for example, after every 100 pcs reported. So in above example number of iterations for data collection could vary from 10 - 50.
    We see that there are two fields "Required Data Entries" & "Optional Data Entries" in the Data Collection parameter detail tab but looks like those are for static values but we want this to change based on order quantity.
    Also we noticed another issue with these fields for our scenario, if we use "Required Data Entries" field then user has to collect all the iterations together but that is not possible since we are collecting after reporting a certain qty. If we use "Optional Data Entries" then system allow the user to collect multiple times but the pop-up does not indicate how many iterations are already collected which is confusing for the users.
    Has anyone else had any experience with a similar scenario?
    Thanks in advance!
    -Venkat

    Hello Venkat,
    To collect data against the same SFC several times you should enable the corresponding System Rule 'Allow Multiple Data Colelction'. The "Optional Data Entries" rather controls the number of optional entries that you can enter (i.e. you measure temperature of SFC and need to enter several measures for a single Data Collection).
    As long as you enable the system rule, it will be up to you when to collect it. But there is no standard functionality to force it after certain Qty of SFC processed. You'll need a customization for it.
    Br, Alex.

  • How to pass a Java arraylist as a parameter to a StoredProcedureCall

    I need to invoke a stored procedurecall which takes in a collection parameter represented as a nested table. I need to pass a java ArrayList object to it. How can I pass this parameter to the stored procedure using StoredProcedureCall class.

    Hello,
    Check out
    Is possible to pass array/list as parameter in TopLink StoredProcedureCall?
    for some more information on using VARRAYs in 10.1.3. TopLink 11 has a feature that converts VARRAYs to/from collection types for you. An example using "myProcedure" that has an inout parameter "names" defined as type "NAMELIST_TYPE" would be:
        StoredProcedureCall sqlcall = new StoredProcedureCall();
        sqlcall.setProcedureName("myProcedure");
        sqlcall.addUnamedInOutputArgument("names", "names", Types.ARRAY, "NAMELIST_TYPE", ArrayList.class);
        DataReadQuery query = new DataReadQuery();
        query.addArgument("names");
        query.setCall(sqlcall);
        Vector args = new Vector();
        ArrayList names = new ArrayList();
        names.add("firstname1");
        names.add("firstname2");
        args.add(names);
        //DataReadQuery returns a collection of DatabaseRecords
        results = (Vector)getSession().executeQuery(query, args);
        //getting one record from the list:
        names =((ArrayList)((DatabaseRecord)results.get(0)).get("names"))This is just a simple example. More complex nested types can be done by providing a ObjectRelationalDatabaseField parameter describing the type, but I dont have any examples showing this handy.
    Hope this example helps,
    Chris

  • SCCM 2012 report w/ selectable collection

    I am trying to create a report with a selectable collection parameter.  The original query I'm using is as follows (Stolen from
    http://blogs.technet.com/b/infratalks/archive/2013/09/10/sccm-2012-reporting-get-system-serial-number-amp-create-custom-ssrs-report.aspx):
    Select sys.Name0 Machine, CS.UserName0 'User Name',OS.Caption0 OS, OS.CSDVersion0 'Service Pack',CS.Manufacturer0 Manufacturer,CS.Model0 Model,BIOS.SerialNumber0 'Serial Number',RAM.Capacity0 Memory, cs.SystemType0
    From v_R_System SYS
      left join v_GS_COMPUTER_SYSTEM CS on sys.Name0=cs.Name0
      left join v_GS_PC_BIOS BIOS on sys.ResourceID=bios.ResourceID
      left join v_GS_OPERATING_SYSTEM OS on sys.ResourceID=OS.ResourceID
      left join v_GS_PHYSICAL_MEMORY RAM on sys.ResourceID=ram.ResourceID
      --Where sys.Name0 = @variable
      order by sys.Name0
    This works fine, but it gives me that information for EVERY machine in our infrastructure globally.  I am only interested in getting this information from machines in certain collections and I want to be able to select the collection each time I run
    the report.  I found this article:
    http://it.peikkoluola.net/2013/06/02/report-with-a-selectable-collection-parameter-sql/ and followed the steps, but cannot run the report successfully.  I'm guessing it has something to do with needing to modify my query, but I am a newb with SQL and
    have no clue what or where I should be tweaking.  Just adding "WHERE(dbo.v_FullCollectionMembership.CollectionID
    = @COLLID)" gives me a syntax error.  Moving it above "Order by sys.name0" gives an error about not being bound to anything, which makes sense but as I mentioned, I don't know what to tweak.  Help!  Thanks.

    Select sys.Name0 Machine, CS.UserName0 'User Name',OS.Caption0 OS, OS.CSDVersion0 'Service Pack',CS.Manufacturer0 Manufacturer,CS.Model0 Model,BIOS.SerialNumber0 'Serial Number',RAM.Capacity0 Memory, cs.SystemType0
    From v_R_System SYS
      left join v_GS_COMPUTER_SYSTEM CS on sys.Name0=cs.Name0
      left join v_GS_PC_BIOS BIOS on sys.ResourceID=bios.ResourceID
      left join v_GS_OPERATING_SYSTEM OS on sys.ResourceID=OS.ResourceID
      left join v_GS_PHYSICAL_MEMORY RAM on sys.ResourceID=ram.ResourceID
      join v_fullcollectionmembership fcm on fcm.resourceid=sys.resourceid
      Where fcm.collectionid = @COLLID
      order by sys.Name0
    Try the above, note that @COLLID is a placeholder for a variable.  It is presumed that you are creating this using Report Builder 3.0 (or better) or some other SQL tool to create reports for use on your SRS reporting point.  If you happen
    to be using Report Builder, once you save the above, under parameters you'd have a place for COLLID.  Now, what you want is to be able to have that parameter be populated with your collection names, so that you can select from the list when the report
    is run.
    So... another DataSet, with a query like:
    select collectionid, name
    from v_collection
    order by name
    Then, back to your parameters, COLLID, available values, Get values from a query, and you'll want to use that dataset you just made, and Value field is collectionid, and Label field is Name.
    If you want to test the top query in regular sql, don't use @collID.  figure out the collectionid of a specific collection, and put in where fcm.collectionid='ABC00012'
    Standardize. Simplify. Automate.

  • Generic Method, How parameter type is determined

    For method
    <T> void fromArrayToCollection(T[] a, Collection<T> c) { ... } Why does
    fromArrayToCollection(sa, co);passes and
    fromArrayToCollection(oa, cs); fails.
    oa - Object Array, Object[]
    cs - Collection of String, Collection<String>
    sa - String Array, String[]
    co - Collection of Object, Collection<Object>
    What are the rules governing the type of T inferred by compiler?

    epiphanetic wrote:
    I think you still haven't fully understood the issue.
    I suggest, you also read the same generics tutorial by Gilad Bracha, section 6 from where I found this issue :). Ha! But I think it's misleading that that section uses arrays.
    In his words "It will generally infer the most specific type argument that will make the call type-correct." Its also mentioned that collection parameter type has to be supertype of Array parameter type but no reason is given. I wonder why it fails to infer correct type in second case.Assume you passed in an array of Objects, and a Collection of Strings, and it was possible that T would then be Object. Using Bracha's example implementation:
    static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
       for (T o : a) {
          c.add(o); // correct
    }Now imagine you had this code making use of it:
    Object[] objects = {Integer.valueOf(1), "hi", new Object()};
    Collection<String> strings = new LinkedList<String>();
    fromArrayToCollection(objects, strings);
    String string = strings.iterator().next(); //get first String, which is actually an IntegerTrying to get the first String would give a ClassCastException. So clearly that method cannot not be safely invoked.
    The reason I think he's confusing things by using the array is because you might get it in your head that this would be OK:
    static <T> void fromCollectionToCollection(Collection<T> one, Collection<T> two) {
       for ( T t : one ) {
          two.add(t);
    Collection<Object> col1; Collection<String> col2;
    doSomething(col1, col2);When clearly it's unsafe, as now your Collection of Strings might have a non-String in it! That's why I said this is more a nuance of generic arrays than of type inference proper.

  • Target Data Collection in ASCP

    Hi,
    I was NOT able to see "Target Data Collection" parameter in LOV of Data Collection Concurrent Program.I was able to "see" ONLY Complete Refresh Parameter in LOV.
    Is there any Profile Option?
    Regards
    NTGR

    set "purge previously collected data" to 'NO' in the parameter list. you will able to see "targeted collection" and "Net change Collection" in Collection Method parameter LOV.
    Regards
    Abhishek

  • Question regarding SYS_REFCURSOR

    Hello,
    Here is my procedure which will get the set of result into SYS_REFCURSOR as OUT parameter.
    The problem is :
    if p_job is null then we will get "ORA-01006: bind variable does not exist"
    Could anybody please let me know how to solve this problem, or please provide better way to put the set of result into SYS_REFCURSOR.
    Thanks in advance!
    CREATE OR REPLACE PROCEDURE pr_test
    (p_start_date IN DATE,
    p_end_date IN DATE,
    p_job IN varchar2,
    result_set IN OUT SYS_REFCURSOR)
    AS
    v_sql_string varchar2(2000);
    BEGIN
    v_sql_string := 'SELECT * FROM emp WHERE HIREDATE between :1 AND :2';
    IF p_job is not null THEN
    v_sql_string := v_sql_string || ' AND job = :3';
    END IF;
    OPEN result_set
    FOR v_sql_string USING p_start_date, p_end_date, p_job;
    END pr_test;
    /

    Hello,
    I did some test with DBMS_SQL, and was able to solve my previous problem (determining the number of bind variables and bind them at run-time) with DBMS_SQL.BIND_VARIABLE.
    However, I could not figure out how to pass the cursor to client application. This function will be called by other web-based application. Could anybody please help on this or provide me other way to solve both issues (bind variables and pass cursor to client application).
    Here is the two functions:
    Function F will pass the cursor to client application (I used sqlplus here). But I am not able to bind variables at run-time. For example, if p_job/p_start/p_end is not null, then I need to add them into V_SQL and USING Clause......
    Function F2 will let me bind the variables at run-time. However, it does not let me pass the cursor to client application, because of the restriction of DBMS_SQL.TO_REFCURSOR.
    Thanks in advance!!!
    create or replace function F (p_deptno emp.deptno%type,
    p_start emp.hiredate%type,
    p_end emp.hiredate%type,
    p_job emp.job%type)
    return sys_refcursor
    as
    rec sys_refcursor;
    v_sql varchar2(1000);
    begin
    v_sql := 'select * from emp where deptno = :1';
    open rec for v_sql using p_deptno;
    return rec;
    end;
    Function created.
    SQL> var rec refcursor
    SQL> execute :rec := f(10, null, null, null);
    PL/SQL procedure successfully completed.
    SQL> print rec
    EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
    7782 CLARK MANAGER 7839 09-JUN-81 3450 10
    7839 KING PRESIDENT 17-NOV-81 6000 10
    7934 MILLER CLERK 7782 23-JAN-82 4300 10
    create or replace function F2(p_deptno emp.deptno%type,
    p_start emp.hiredate%type,
    p_end emp.hiredate%type,
    p_job emp.job%type)
    return sys_refcursor
    AS
    v_sql varchar2(3200);
    v_cursor binary_integer := dbms_sql.open_cursor;
    v_execute binary_integer;
    begin
    v_sql := 'select * from emp where deptno = :deptno';
    dbms_sql.parse(v_cursor, v_sql, dbms_sql.native);
    dbms_sql.bind_variable(v_cursor, 'deptno', p_deptno);
    v_execute := dbms_sql.execute(v_cursor);
    RETURN dbms_sql.to_refcursor(v_cursor);
    end;
    Function created.
    SQL> var rec refcursor
    SQL> execute :rec := f2(10, null, null, null);
    PL/SQL procedure successfully completed.
    SQL> print rec
    ERROR:
    ORA-01001: invalid cursor
    no rows selected

  • Performance: Bulk Insert Oracle 10g

    Following Situation: We have a VISUAL BASIC 6 Application (I know ... VB6 ... ), an XML-File with data and an Oracle 10g database. The XML-File has to be imported in the database.
    Up to now the Application (Via ADO) analyses the XML-File and creates INSERT and UPDATE Stmts and sends them to the DB. The Stmts will be handled within one Transaction and the application sends each INSERT, UPDATE separate to the database.
    But this is a performance desaster... as expected ... :-) The import takes several hours ...
    Now, my task is to increase the performance, but how .....
    I tried several things, but without the real success, e.g. ...
    I performed some tests with the SQl*Loader. The Insert is really fast, but I can't make an Update, so I had to delete the existing data first. But I can't proceed the two steps in one transaction, because of the SQL*Loader.
    I tried to write a stored procedure which accepts an ADO.Recordset as input param and then creates the Insert and Update statements within the DB to reduce network traffic, but I didn't find a way to handle a ADO.Recordset as a input parameter for a stored procedure.
    Has someone an idea how I can import the XML file in a fast way into the existing DB (and maybe make an Replace of existing records during the import ...) within one transaction without changing the structure of the DB ??? (Oracle packages?? interface in C++ integrated in VB6....) Is there an way to import the XML-File directly to the DB?
    Thanks in advance for any idea :-))

    I tried to write a stored procedure which accepts an ADO.Recordset as input param ...., but I didn't find a way to handle a ADO.Recordset as a input parameter
    for a stored procedure.Use SYS_REFCURSOR as the parameter type. Bulk collect it into a PL/SQL collection. Use FORALL to soup up the INSERT and UPDATE statements.
    Cheers, APC
    blog: http://radiofreetooting.blogspot.com

  • Creating view to get first row for each table !!

    I am having tables(more than 10) which are related using foreign key and primary key relationship.
    Example:
    Table1:
    T1Prim T1Col1 T1Col2
    Table2
    T2For T2Prim T2Col1 T2Col2 T2Col3
    (here T2For will have value same as T1Prim and in my design it has same column name i.e. T1Prim)
    Table3
    T3For T3Prim T3Col1 T3Col2 T3Col3
    (here T3For will have value same as T2Prim)
    and so on.
    The data in the tables is like For table1 there will be one record, for table2 there will be one record and for table 3 there are more than one records.
    Can i view either the first record for each of them or all records from each of them by writing the following view.
    I have written a view like this:
    Create or replace view test (T1Prim,T1Col1, T1Col2,T2Prim,T2Col1 T2Col2, T2Col3, T3Prim,T3Col1, T3Col2, T3Col3)
    As
    Select
    Table1.T1Prim,
    Table1.T1Col1,
    Table1.T1Col2,
    Table2.T2Prim,
    Table2.T2Col1,
    Table2.T2Col2,
    Table2.T2Col3,
    Table3.T3Prim,
    Table3.T3Col1,
    Table3.T3Col2,
    Table3.T3Col3
    From
    Table1,
    Table2,
    Table3
    where
    Table1.Prim = Table2.For
    and Table2.Prim = Table3.For
    When i ran the select statement on the view I am not getting any data. Whereas there is data when select is ran on individual table.
    Can someone please tell me where i am goofing.
    Thanks in the anticipation that i will get some hint to solve this.
    Eagerly waiting for reply.
    Thanks !!

    I mean use a collection :
    Collection Methods
    A collection method is a built-in function or procedure that operates on collections and is called using dot notation. The methods EXISTS, COUNT, LIMIT, FIRST, LAST, PRIOR, NEXT, EXTEND, TRIM, and DELETE help generalize code, make collections easier to use, and make your applications easier to maintain.
    EXISTS, COUNT, LIMIT, FIRST, LAST, PRIOR, and NEXT are functions, which appear as part of an expression. EXTEND, TRIM, and DELETE are procedures, which appear as a statement. EXISTS, PRIOR, NEXT, TRIM, EXTEND, and DELETE take integer parameters. EXISTS, PRIOR, NEXT, and DELETE can also take VARCHAR2 parameters for associative arrays with string keys. EXTEND and TRIM cannot be used with index-by tables.
    For more information, see "Using Collection Methods".
    Syntax
    Text description of the illustration collection_method_call.gif
    Keyword and Parameter Description
    collection_name
    This identifies an index-by table, nested table, or varray previously declared within the current scope.
    COUNT
    COUNT returns the number of elements that a collection currently contains, which is useful because the current size of a collection is not always known. You can use COUNT wherever an integer expression is allowed.
    For varrays, COUNT always equals LAST. For nested tables, normally, COUNT equals LAST. But, if you delete elements from the middle of a nested table, COUNT is smaller than LAST.
    DELETE
    This procedure has three forms. DELETE removes all elements from a collection. DELETE(n) removes the nth element from an index-by table or nested table. If n is null, DELETE(n) does nothing. DELETE(m,n) removes all elements in the range m..n from an index-by table or nested table. If m is larger than n or if m or n is null, DELETE(m,n) does nothing.
    EXISTS
    EXISTS(n) returns TRUE if the nth element in a collection exists. Otherwise, EXISTS(n) returns FALSE. Mainly, you use EXISTS with DELETE to maintain sparse nested tables. You can also use EXISTS to avoid raising an exception when you reference a nonexistent element. When passed an out-of-range subscript, EXISTS returns FALSE instead of raising SUBSCRIPT_OUTSIDE_LIMIT.
    EXTEND
    This procedure has three forms. EXTEND appends one null element to a collection. EXTEND(n) appends n null elements to a collection. EXTEND(n,i) appends n copies of the ith element to a collection. EXTEND operates on the internal size of a collection. So, if EXTEND encounters deleted elements, it includes them in its tally. You cannot use EXTEND with index-by tables.
    FIRST, LAST
    FIRST and LAST return the first and last (smallest and largest) subscript values in a collection. The subscript values are usually integers, but can also be strings for associative arrays. If the collection is empty, FIRST and LAST return NULL. If the collection contains only one element, FIRST and LAST return the same subscript value.
    For varrays, FIRST always returns 1 and LAST always equals COUNT. For nested tables, normally, LAST equals COUNT. But, if you delete elements from the middle of a nested table, LAST is larger than COUNT.
    index
    This is an expression that must yield (or convert implicitly to) an integer in most cases, or a string for an associative array declared with string keys.
    LIMIT
    For nested tables, which have no maximum size, LIMIT returns NULL. For varrays, LIMIT returns the maximum number of elements that a varray can contain (which you must specify in its type definition).
    NEXT, PRIOR
    PRIOR(n) returns the subscript that precedes index n in a collection. NEXT(n) returns the subscript that succeeds index n. If n has no predecessor, PRIOR(n) returns NULL. Likewise, if n has no successor, NEXT(n) returns NULL.
    TRIM
    This procedure has two forms. TRIM removes one element from the end of a collection. TRIM(n) removes n elements from the end of a collection. If n is greater than COUNT, TRIM(n) raises SUBSCRIPT_BEYOND_COUNT. You cannot use TRIM with index-by tables.
    TRIM operates on the internal size of a collection. So, if TRIM encounters deleted elements, it includes them in its tally.
    Usage Notes
    You cannot use collection methods in a SQL statement. If you try, you get a compilation error.
    Only EXISTS can be applied to atomically null collections. If you apply another method to such collections, PL/SQL raises COLLECTION_IS_NULL.
    You can use PRIOR or NEXT to traverse collections indexed by any series of subscripts. For example, you can use PRIOR or NEXT to traverse a nested table from which some elements have been deleted.
    EXTEND operates on the internal size of a collection, which includes deleted elements. You cannot use EXTEND to initialize an atomically null collection. Also, if you impose the NOT NULL constraint on a TABLE or VARRAY type, you cannot apply the first two forms of EXTEND to collections of that type.
    If an element to be deleted does not exist, DELETE simply skips it; no exception is raised. Varrays are dense, so you cannot delete their individual elements.
    PL/SQL keeps placeholders for deleted elements. So, you can replace a deleted element simply by assigning it a new value. However, PL/SQL does not keep placeholders for trimmed elements.
    The amount of memory allocated to a nested table can increase or decrease dynamically. As you delete elements, memory is freed page by page. If you delete the entire table, all the memory is freed.
    In general, do not depend on the interaction between TRIM and DELETE. It is better to treat nested tables like fixed-size arrays and use only DELETE, or to treat them like stacks and use only TRIM and EXTEND.
    Within a subprogram, a collection parameter assumes the properties of the argument bound to it. So, you can apply methods FIRST, LAST, COUNT, and so on to such parameters. For varray parameters, the value of LIMIT is always derived from the parameter type definition, regardless of the parameter mode.
    Examples
    In the following example, you use NEXT to traverse a nested table from which some elements have been deleted:
    i := courses.FIRST; -- get subscript of first element
    WHILE i IS NOT NULL LOOP
    -- do something with courses(i)
    i := courses.NEXT(i); -- get subscript of next element
    END LOOP;
    In the following example, PL/SQL executes the assignment statement only if element i exists:
    IF courses.EXISTS(i) THEN
    courses(i) := new_course;
    END IF;
    The next example shows that you can use FIRST and LAST to specify the lower and upper bounds of a loop range provided each element in that range exists:
    FOR i IN courses.FIRST..courses.LAST LOOP ...
    In the following example, you delete elements 2 through 5 from a nested table:
    courses.DELETE(2, 5);
    In the final example, you use LIMIT to determine if you can add 20 more elements to varray projects:
    IF (projects.COUNT + 20) < projects.LIMIT THEN
    -- add 20 more elements
    Related Topics
    Collections, Functions, Procedures
    http://download-west.oracle.com/docs/cd/B10501_01/appdev.920/a96624/13_elems7.htm#33054
    Joel P�rez

  • Problem with ejb 3.0 entity beans with manyToMany relationship

    Hello everyone!
    I am using struts 1.2.9 and java ee 5 sdk update 2 for my enterprise application. Besides others i have these entity beans Targetgroup.java and City.java, (i would upload file but i do not know how:)
    with manytomany relationship with join table.
    when user updates Targetgroup, by clicking on web page with checkboxes and textfields, struts dispatch action calls following method stateless bean:
    public void update(String firmId, String targetgroupId, String newGender, String newMinYearsOld, String newMaxYearsOld, String[] newCities) {
    TargetgroupPK pkForUpdate = new TargetgroupPK(targetgroupId, firmId);
    Targetgroup targetgroupForUpdate = find(pkForUpdate);
    targetgroupForUpdate.setGender(newGender);
    targetgroupForUpdate.setMinyearold(Integer.parseIn t(newMinYearsOld));
    targetgroupForUpdate.setMaxyearold(Integer.parseIn t(newMaxYearsOld));
    //pronalazenje gradva za koje je vezana ciljna grupa
    Collection<City> newCitiesCollection = new ArrayList<City>();
    for(int i = 0; i < newCities.length; i++){
    String tmp_city_name = newCities;
    City city_obj = cityFacade.find(tmp_city_name);
    newCitiesCollection.add(city_obj);
    targetgroupForUpdate.setCityidCollection(newCities Collection);
    parameter newCities represents names of cities which user checked on his update page. When the page is showen to him some cities are allready check because they were connected with Targetgruoup when it was created (targetgroup).
    this code throws following exception:
    [#|2007-07-26T12:13:36.993+0200|SEVERE|sun-appserver-pe9.0|javax.enterprise.system.container.web|_Threa dID=16;_ThreadName=httpWorkerThread-8080-0;_RequestID=f79d9c50-86b0-4b6c-96ab-97956dfb39c1;|StandardWrapperValve[action]: Servlet.service() for servlet action threw exception
    javax.ejb.EJBException: Transaction aborted; nested exception is: javax.transaction.RollbackException: Transaction marked for rollback.
    javax.transaction.RollbackException: Transaction marked for rollback.
    at
    .com.sun.enterprise.web.connector.grizzly.WorkerTh read.run(WorkerThread.java:75)
    javax.ejb.EJBException: Transaction aborted; nested exception is: javax.transaction.RollbackException: Transaction marked for rollback.
    at com.sun.ejb.containers.BaseContainer.completeNewTx (BaseContainer.java:3659)
    at com.sun.ejb.containers.BaseContainer.postInvokeTx( BaseContainer.java:3431)
    at com.sun.ejb.containers.BaseContainer.postInvoke(Ba seContainer.java:1247)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHan dler.invoke(EJBLocalObjectInvocationHandler.java:1 92)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHan dlerDelegate.invoke(EJBLocalObjectInvocationHandle rDelegate.java:71)
    at $Proxy149.update(Unknown Source)
    at audiotel.sms.actions.backoffice.TargetgroupDispatc hAction.updateOrDelete(TargetgroupDispatchAction.j ava:132)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Native MethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(De legatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.struts.actions.DispatchAction.dispatchM ethod(DispatchAction.java:270)
    at org.apache.struts.actions.DispatchAction.execute(D ispatchAction.java:187)
    at org.apache.struts.action.RequestProcessor.processA ctionPerform(RequestProcessor.java:431)
    at org.apache.struts.action.RequestProcessor.process( RequestProcessor.java:236)
    at org.apache.struts.action.ActionServlet.process(Act ionServlet.java:1196)
    at org.apache.struts.action.ActionServlet.doPost(Acti onServlet.java:432)
    at javax.servlet.http.HttpServlet.service(HttpServlet .java:727)
    com.sun.enterprise.web.connector.grizzly.WorkerThr ead.run(WorkerThread.java:75)
    |#]
    exceprion is throwen ONLY when in parameter newCities are city names allready connected to Targetgroup. when NewCities contains names of
    City objects which are not connected to Targetgroup it works fine, but it's of no use for me, because user must be able to add or remove certian cities from relaionship with Targetgroup. I think it's because there are rows in join table that contain primary keys of city and targetgroup which are connected so perisistence manager cann't write them again.
    i thought it was going to figure it out by itself, and only update those rows.
    Does anyone know what is the problem and solution?
    Thanks! (forgive my spelling errors :)

    solved the problem!
    I moved code from sesion bean to struts action as follows:
    CityFacadeLocal cityFacade = lookupCityFacade();
    //prikupljanje novih podataka o ciljnoj grupi
    String newGender = ctf.getGender();
    String newMaxYears = ctf.getMaxyears();
    String newMinYears = ctf.getMinyears();
    String[] newSelectedCities = ctf.getSelectedCities();
    //niz imena gradova se prevodi u kolekcju objekata City
    Collection<City> newCitiesObjCollection = new Vector<City>();
    for(int i = 0; i < newSelectedCities.length; i++){
    String tmpCityName = newSelectedCities;
    City tmpCityObj = cityFacade.find(tmpCityName);
    newCitiesObjCollection.add(tmpCityObj);
    //setovanje novih podataka
    targetgroupForUD.setGender(newGender);
    targetgroupForUD.setMinyearold(Integer.parseInt(newMinYears));
    targetgroupForUD.setMaxyearold(Integer.parseInt(newMaxYears));
    targetgroupForUD.setCityidCollection(newCitiesObjCollection);
    //pozivanje update metdoe u session beany
    targetgroupFacade.edit(targetgroupForUD);
    //korisnik se vraca na stranu sa svim postojecim ciljnim grupama
    forward = mapping.findForward("backend.targetgroups");
    and now it works fine. I guess probelm was same transaction scope for Targetgroup and City entities. Now when they are separated it works.
    Thanks!

  • Query on Lock object

    Hi,
    I need to lock the Custom table based on company code.
    I have an Internal table with list of company codes. Now I need to lock the table for All the company codes there in ITAB.
    I am doing like this.
    Before Save:
    LOOP AT it_lock INTO wa_t001.
              CALL FUNCTION 'ENQUEUE_EYFR1FIT_GIFTREF'
                EXPORTING
                  mode_yfr1fit_gift_ref = 'E'
                  mandt                 = sy-mandt
                  bukrs                 = wa_t001-bukrs.
              X_BUKRS                     = ' '
              _SCOPE                      = '2'
              _WAIT                       = ' '
              _COLLECT                    = ' '
            EXCEPTIONS
              FOREIGN_LOCK                = 1
              SYSTEM_FAILURE              = 2
              OTHERS                      = 3
              IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
              ENDIF.
              CLEAR wa_t001.
            ENDLOOP.
    After Save
    LOOP AT it_lock INTO wa_t001.
        CALL FUNCTION 'DEQUEUE_EYFR1FIT_GIFTREF'
          EXPORTING
            mode_yfr1fit_gift_ref = 'E'
            mandt                 = sy-mandt
            bukrs                 = wa_t001-bukrs.
        X_BUKRS                     = ' '
        _SCOPE                      = '3'
        _SYNCHRON                   = ' '
        _COLLECT                    = ' '
        CLEAR wa_t001.
      ENDLOOP.
    Please let me know is that the write way?
    Or do we need to pass any extra parameters?
    what is the COLLECT parameter for?
    Thanks,
    Sandeep

    Hi,
    Refer following code,
    *--Check if monitor table is initial
      IF NOT gt_hdrlog[] IS INITIAL.
        LOOP AT gt_hdrlog INTO ls_monitor.
    *--Lock the DB table ZAPT_AR_MONITOR before updation
          CALL FUNCTION 'ENQUEUE_EZAPT_AR_MONITOR'
            EXPORTING
              mode_zapt_ar_monitor = lc_x                 "Check
              mandt                = sy-mandt             "Cient
              doc_num              = ls_monitor-doc_num   "IDOC number
              x_doc_num            = lc_x                 "Check
            EXCEPTIONS
              foreign_lock         = 1
              system_failure       = 2
              OTHERS               = 3.
          IF sy-subrc NE 0.
            WAIT UP TO 1 SECONDS.
          ELSE.
    *--If DB table is locked then insert data into custom table
            INSERT into zapt_ar_monitor values ls_monitor.
            IF sy-subrc NE 0.
    *--Update custom table
              UPDATE zapt_ar_monitor FROM ls_monitor.
            ENDIF.
          ENDIF.
    *--Unlock the table after updation
          CALL FUNCTION 'DEQUEUE_EZAPT_AR_MONITOR'
            EXPORTING
              mode_zapt_ar_monitor = lc_x                 "Check
              mandt                = sy-mandt             "Client
              doc_num              = ls_monitor-doc_num   "IDOC Number
              x_doc_num            = lc_x.                "Check
    *--Clear the work areas
          CLEAR : ls_monitor.
        ENDLOOP.
      ENDIF.
    Regards,
    Prashant

Maybe you are looking for

  • CJS-30059 Java EE Engine configuration error FCO-00011 The step configCAF

    Hallo trying to install SAP EHP1 for NW 7.0 Developer Workplace for AS Java (no Abap) I get the error: CJS-30059 Java EE Engine configuration error. FCO-00011 The step configCAF with step key |NW_Workplace|ind|ind|ind|ind|0|0|NW_Onehost|ind|ind|ind|i

  • RMI server doesn't reliably start

    I have a simple RMI server with one object that has one method: public interface Foo extends Remote {       // the Blah class is Serializable       java.util.ArrayList <Blah> getListOfBlahs (String name); public class FooImpl impelments Foo {     jav

  • Windows does not detect my sound card

    Hello, I have a thinkcentre m58p dt. I had to reinstall windows(same version which was already installed before) but since I did it integratedsound behaves a strange way. Windows detects it and it appears in the device windows menu. I can use headpho

  • A slideshow widget worked while testing on my website but won't work on the client's server/site

    The Spry widget slideshow I inserted operated properly while I tested it on my website: http://www.camdesign.biz/TotalProperty2/gallery_stonewalls.html. When I uploaded all of the files to my clients' server the slideshow does not work. (all the othe

  • Cannot connect to 9ifs

    Dear everyone, can you tell me the main reasons caused such problem? Thank you very much for your help and your time. the source code is listed below, // Copyright (c) 2001 Oracle Corporation import oracle.ifs.beans.LibraryService; import oracle.ifs.