BULK COLLECT in select query inside a function

Hi All,
My query is :
SELECT col1,col2,col3 FROM table_a; --( consider this is a long running query with lot of joins)
Need to know how can i get the output of the above query from a function using BULK COLLECT.
and i tried this:
CREATE OR REPLACE TYPE tab_a_row
AS OBJECT (
col1 number(20),
col2 number(20),
col2 number(20)) ;
create or replace type tab_a_nt as table of tab_a_row;
create or replace function get_table_a
return sys_refcursor
is
tab_a_recs tab_a_nt;
rv sys_refcursor;
begin
SELECT tab_a_row(col1,col2,col3) BULK COLLECT INTO tab_a_recs FROM table_a;
open rv for select * from table(tab_a_recs);
return rv;
end;
Function created successfully. and i exec this from sql plus using
SQL> var rc refcursor;
SQL> exec :rc := get_table_a;
BEGIN :rc := get_table_a; END;
ERROR at line 1:
ORA-22905: cannot access rows from a non-nested table item
ORA-06512: at "GET_TABLE_A", line 12
ORA-06512: at line 1
Kindly share your ideas on how to use bulk collect and get set of outputs from a function.
Edited by: 887268 on Apr 18, 2013 3:10 AM

>
If i use refcursor , then the JAVA code needs to be changed accordinglyto get the refcursor output.
>
Well, of course. Java has to know what the sql projection is. How else will it know how many columns there are and their datatypes.
But that is true no matter what method you use.
>
But if i use a PLSQL COLLECTION TYPE (nested tables ) , then i can get output as ,
select * from table(function_name(input1,input2));
>
No - using the 'table' function mean you are calling a PIPELINED function.
This is a sample of a PIPELINED procedure.
-- 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))Or your function could return a collection like the example from this thread this morning.
Example of Collection as datatype of a function’s return value
CREATE OR REPLACE TYPE enamelist as VARRAY(20) of VARCHAR2(20)
/* Formatted on 4/18/2013 4:06:47 PM (QP5 v5.126.903.23003) */
CREATE OR REPLACE FUNCTION ename_fn
RETURN enamelist
AS
v_cursor_main enamelist := enamelist ();
BEGIN
SELECT ename
BULK COLLECT
INTO v_cursor_main
FROM emp;
RETURN v_cursor_main;
EXCEPTION
WHEN OTHERS
THEN
RETURN v_cursor_main;
END;
select * from table(ename_fn()) from dual;
COLUMN_VALUE
SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER

Similar Messages

  • Problem with select query inside a function.

    Hi,
    i have created a function as
    create or replace function "NEW"
    (emp in number,
    s_date in DATE,
    e_date in DATE)
    return number
    is
    v_alo number default 0;
    v_alo2 number default 0;
    v_date date;
    begin
    select sum(allocation_percent) into v_alo from employeeproject where start_date < s_date and end_date > e_date and pid != 'BPDE-KER12' and employee_id = emp;
    select allocation_percent into v_alo2 from employeeproject where start_date < s_date and end_date > e_date and pid = 'BPDE-KER12' and employee_id = emp;
    select max(end_date) into v_date from employeeproject where employee_id=emp having max(end_date) <= S_DATE;
    if v_alo < 100 then
    return 1;
    else if v_alo2 = 100 then
    return 2;
    else if v_date < s_date then
    return 3;
    else
    return 4;
    end if;
    end if;
    end if;
    exception
    when NO_DATA_FOUND then
    return 5;
    end;it is compiled correctly.
    when executing the function with
    select abc.a,new(a,'03-jan-2011','04-jan-2011') "status" from abc where new(a,'03-jan-2011','04-jan-2011') in (1,2,3,4);it is returning
    A status
    1 5
    2 5
    3 5
    instead of
    A status
    1 1
    2 2
    3 3
    and when i comment any two select statements then some part of my ans is correct.
    unable to understand the behaviour.
    can any pls help me understand it.
    Thanks,
    hari

    Hi,
    thanks for the reply, and sorry for my ugly code.
    i am using Oracle database 10g express edition.
    Case could be a option to use but i need to figure why my query is not returning any value when used together.
    my requirement is to find
    the employees who are have allocation percent sum < 100 for a defined period(excluding pid=BPDE-KER12) and
    employee who is mapped to pid=BPDE-KER12 not in my first requirement in that period and
    the employees whose latest end date is less than the new start date.
    i have tried the new modified code as you said but this time it returns null, not even exceptions running.
    i divide my requirement into three functions which will return value.
    1.  create or replace function "NEW4"
    (emp in number,
    s_date in DATE,
    e_date in DATE)
    return number
    is
    v_alo number default 0;
    v_alo2 number default 0;
    v_date date;
    begin
    --to check if the employee total percentage is <100 then return 1 else return 4
    select sum(allocation_percent) into v_alo from pm_employee_project
    where
    start_date < s_date and end_date > e_date and pid !='BPDE-KER12' and employee_id = emp;
    if v_alo < 100 then
    return 1;
    elsif v_alo2 = 100 then
    return 2;
    elsif v_date < s_date then
    return 3;
    else
    return 4;
    end if;
    exception
    when NO_DATA_FOUND then
    return 5;
    end;
    then,
    select abc.a,NEW4(a,'03-jan-2011','30-jan-2011') "STATUS" from abc
    result,
    A STATUS
    1 *1*
    2 4
    3 4 2.create or replace function "NEW5"
    (emp in number,
    s_date in DATE,
    e_date in DATE)
    return number
    is
    v_alo number default 0;
    v_alo2 number default 0;
    v_date date;
    begin
    --To select employee who are in a specific pid.
    select allocation_percent into v_alo2 from pm_employee_project where
    start_date < s_date and end_date > e_date and pid = 'BPDE-KER12' and
    employee_id = emp;
    if v_alo2 = 100 then
    return 2;
    elsif v_alo < 100 then
    return 1;
    elsif v_date < s_date then
    return 3;
    else
    return 4;
    end if;
    exception
    when NO_DATA_FOUND then
    return 5;
    end;
    then,
    select abc.a,NEW5(a,'03-jan-2011','30-jan-2011') "STATUS" from abc
    Result,
    A STATUS
    1 5
    2 *2*
    3 5 3.   create or replace function "NEW6"
    (emp in number,
    s_date in DATE,
    e_date in DATE)
    return number
    is
    v_alo number default 0;
    v_alo2 number default 0;
    v_date date;
    begin
    --to select the employee whose project end date is less thann the new date.
    select max(end_date) into v_date from pm_employee_project where
    employee_id=emp having max(end_date) <= S_DATE;
    if v_alo2 = 100 then
    return 2;
    elsif v_alo = 100 then
    return 1;
    elsif v_date < s_date then
    return 3;
    else
    return 4;
    end if;
    exception
    when NO_DATA_FOUND then
    return 5;
    end;
    then,
    select abc.a,NEW6(a,'03-jan-2011','30-jan-2011') "STATUS" from abc
    Result,
    A STATUS
    1 5
    2 5
    3 *3* so my function works properly individually, but i want all the three conditions in a single function with same order as above 1 then 2 and then 3.
    and when i try to do it that way i am not getting my result as
    A STATUS
    1 *1*
    2 *2*
    3 *3*
    so how can i proceed.
    my input table values,
    select * from abc
    A B C
    1 2 2
    2 1 3
    3 1 2
    select * from pm_employee_project
    varchar2 varchar2 date date date varchar2
    EMPLOYEE_ID PID START_DATE END_DATE ALLOCATION_PERCENT SUPERVISOR_ID
    1 10 02-JAN-11 31-JAN-11 89 -
    1 20 05-JAN-11 20-JAN-11 9 -
    1 BPDE-KER12 21-JAN-11 31-JAN-11 11 -
    2 BPDE-KER12 01-JAN-11 31-JAN-11 100 -
    3 30 01-JAN-10 01-JAN-11 100

  • Select query inside PL/SQL block.

    Hello Experts,
    I am just a beginner with PL/SQL.
    If I write a select query from client like SQL dev and fire it against a database, it gives me result.
    Eg: select * from employee;
    Now when I use the same Query inside a PL/SQL block suppose:
    Declare
    begin
    select * from employee;
    end;
    This gives error on execution, mentioning that an INTO is expected etc...
    I have doubts here:
    1. Can't I use a plain select inside a PL/SQL block (if so why?)
    I know this is kind of very basic question, I tried searching this on the forum but could not find the thread, please redirect me to the link if this is already answered.

    user8578271 wrote:
    Hello Experts,
    I am just a beginner with PL/SQL.
    If I write a select query from client like SQL dev and fire it against a database, it gives me result.
    Eg: select * from employee;
    Now when I use the same Query inside a PL/SQL block suppose:
    Declare
    begin
    select * from employee;
    end;
    This gives error on execution, mentioning that an INTO is expected etc...
    I have doubts here:
    1. Can't I use a plain select inside a PL/SQL block (if so why?) Because when you run a query in a tool like SQL Developer, or SQL*Plus or TOAD etc. then it opens up a cursor and fetches the data into internal memory structures before displaying it, and that is all done automatically and hidden from you. In PL/SQL, there is no interface to display the results of SQL queries, so you have to specifically tell it what to put the data into.
    The syntax is (in basic terms)...
    SELECT column1, column2... columnX
    INTO variables or record structure
    FROM ...Though that can only select a single row of data. If your query returns more than 1 row it will give a TOO_MANY_ROWS exception. If your query returns no rows you will get a NO_DATA_FOUND exception.
    If you need to select multiple rows into variables etc., then you would need to "BULK COLLECT" into a collection/array structure, though this takes up valuable memory on the server and shouldn't be used unless necessary (and you understand the implications of doing it).

  • Nested table collection in select query "in clause" taking long time

    create or replace type t_circuitids is table of varchar2(100);
    --Below anonymous block keeps on running and never ends
    DECLARE
       v_circuitid    t_circuitids;
       v_count number;
       l_circuitids   VARCHAR2 (4000)
          := 'value1,value2,value3,value4,value5';
    BEGIN
    --Below query converts comma concatinated output to list and stores in nested table collection v_circuitids
       WITH a AS
            (SELECT ',' || l_circuitids || ',' AS circuitid
               FROM DUAL)
       SELECT DISTINCT TRIM (SUBSTR (circuitid,
                                     INSTR (circuitid, ',', 1, LEVEL) + 1,
                                       INSTR (circuitid, ',', 1, LEVEL + 1)
                                     - INSTR (circuitid, ',', 1, LEVEL)
                                     - 1
                            ) cid
       BULK COLLECT INTO v_circuitid
                  FROM a
            CONNECT BY LEVEL <
                             LENGTH (circuitid)
                             - LENGTH (REPLACE (circuitid, ','));
       SELECT COUNT (1)
         INTO v_count
         FROM table
        WHERE name IN (SELECT COLUMN_VALUE
                                          FROM TABLE (v_circuitid));
    END;
    --I got the issue, query "SELECT COLUMN_VALUE FROM TABLE (v_circuitid)" which is used in above code is responsible for this.
    --Same code works fine in Development and Test environments, But in prod it keeps on running
    --I solved this issue by creating a temp table, loading all values in collection into the temp table and using that temp table in "in clause"    "
    --Can any one answer why its behaving like this when i use collection in where clause?
    --I am using Oracle 9i

    Below is the code i used
    DECLARE
       v_circuitid    t_circuitids;
       v_count number;
       l_circuitids   VARCHAR2 (4000)
          := 'value1,value2,value3,value4,value5';
    BEGIN
    --Below query converts comma concatinated output to list and stores in nested table collection v_circuitids
       WITH a AS
            (SELECT ',' || l_circuitids || ',' AS circuitid
               FROM DUAL)
       SELECT DISTINCT TRIM (SUBSTR (circuitid,
                                     INSTR (circuitid, ',', 1, LEVEL) + 1,
                                       INSTR (circuitid, ',', 1, LEVEL + 1)
                                     - INSTR (circuitid, ',', 1, LEVEL)
                                     - 1
                            ) cid
       BULK COLLECT INTO v_circuitid
                  FROM a
            CONNECT BY LEVEL <
                             LENGTH (circuitid)
                             - LENGTH (REPLACE (circuitid, ','));
       SELECT COUNT (1)
         INTO v_count
         FROM table
        WHERE name IN (SELECT COLUMN_VALUE
                                          FROM TABLE (ccard(v_circuitid)));
    END;
    And got below error
    ORA-06550: line 27, column 5:
    PL/SQL: ORA-00906: missing left parenthesis
    ORA-06550: line 24, column 4:
    PL/SQL: SQL Statement ignored

  • Using bulk collect with select

    i am working on oracle 10g release 2 .
    My requirement is like this
      1  declare
      2     type id_type is table of fnd_menus.menu_id%type;
      3     id_t id_type;
      4     cursor cur_menu is select menu_name from menu;
      5     type name_type is table of menu.menu_name%type;
      6     name_t name_type;
      7  begin
      8     open cur_menu;
      9     fetch cur_menu bulk collect into name_t;
    10     forall i in name_t.first..name_t.last
    11             select menu_id into id_t(i) from fnd_menus where menu_name = name_t(i);
    12* end;
    SQL> /
                    select menu_id into id_t(i) from fnd_menus where menu_name = name_t(i);
    ERROR at line 11:
    ORA-06550: line 11, column 23:
    PLS-00437: FORALL bulk index cannot be used in INTO clause
    ORA-06550: line 11, column 31:
    PL/SQL: ORA-00904: : invalid identifier
    ORA-06550: line 11, column 3:
    PL/SQL: SQL Statement ignoredSo how i can bulk select into a table the rows that satisfy a particular condition ?

    A forall statement is used bulk execute DML, as can be read [url http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/forall_statement.htm#LNPLS01321]here in the documentation.
    I guess you want something like this:
    SQL> create table menu
      2  as
      3  select 'A' menu_name from dual union all
      4  select 'B' from dual union all
      5  select 'C' from dual
      6  /
    Tabel is aangemaakt.
    SQL> create table fnd_menus
      2  as
      3  select 10 menu_id, 'A' menu_name from dual union all
      4  select 9, 'B' from dual union all
      5  select 8, 'C' from dual union all
      6  select 7, 'D' from dual
      7  /
    Tabel is aangemaakt.
    SQL> declare
      2    type id_type is table of fnd_menus.menu_id%type;
      3    id_t id_type;
      4    cursor cur_menu is select menu_name from menu;
      5    type name_type is table of menu.menu_name%type;
      6    name_t name_type;
      7  begin
      8    open cur_menu;
      9    fetch cur_menu bulk collect into name_t;
    10    forall i in name_t.first..name_t.last
    11      select menu_id into id_t(i) from fnd_menus where menu_name = name_t(i);
    12  end;
    13  /
        select menu_id into id_t(i) from fnd_menus where menu_name = name_t(i);
    FOUT in regel 11:
    .ORA-06550: Regel 11, kolom 25:
    PLS-00437: FORALL-bulkindex kan niet worden gebruikt in INTO-clausule..
    ORA-06550: Regel 11, kolom 33:
    PL/SQL: ORA-00904: : ongeldige ID.
    ORA-06550: Regel 11, kolom 5:
    PL/SQL: SQL Statement ignored.
    SQL> declare
      2    type id_type is table of fnd_menus.menu_id%type;
      3    id_t id_type;
      4  begin
      5    select menu_id
      6      bulk collect into id_t
      7      from fnd_menus
      8     where menu_name in (select menu_name from menu)
      9    ;
    10    for i in 1..id_t.count
    11    loop
    12      dbms_output.put_line(id_t(i));
    13    end loop
    14    ;
    15  end;
    16  /
    10
    9
    8
    PL/SQL-procedure is geslaagd.Regards,
    Rob.

  • Update of a table from a select query with aggregate functions.

    Hello All,
    I have problem here:
    I have 2 tables A(a1, a2, a3, a4, a4....... ) and B( a1, a2, b1, b2, b3). I need to calculate the avg(a4-a3), Max(a4-a3) and Min(a4-a3) and insert it into table B. If the foreign keys a1, a2 already exist in table B, I need to do an update of the computed values into column b1, b2 and b3 respectively, for a1, a2.
    Q1. Is it possible to do this with a single query ? I would prefer not to join A with B because the table A is very large. Also columns b1, b2 and b3 are non-nullable.
    Q2. Also if a4 and a3 are timestamps what is the best way to find the average? A difference of timestamps yields INTERVAL DAY TO SECOND over which the avg function doesn't seem to work. The averages, max and min in my case would be less than a day and hence all I need is to get the data in the hh:mm:ss format.
    As of now I'm using :
    TO_CHAR(TO_DATE(ABS(MOD(TRUNC(AVG(extract(hour FROM (last_modified_date - created_date))*3600 +
    extract( minute FROM (last_modified_date - created_date))*60 +
    extract( second FROM (last_modified_date - created_date)))
    ),86400)),'sssss'),'hh24":"mi":"ss') AS avg_time,
    But this is very long drawn. Something more compact and efficient would be nice.
    Thanks in advance for your inputs.
    Edited by: 847764 on Mar 27, 2011 5:35 PM

    847764 wrote:
    Hi,
    Thanks everyone for such fast replies. Malakshinov's example worked fine for me as far as updating the table goes. As for the timestamp computations, I'm posting additional info: Sorry, I don't understand.
    If Malakshinov's example worked for updating the table, but you still have problems, does that mean you have to do something else besides update the table? If so, what?
    Oracle version : Oracle Database 11g Enterprise Edition Release 11.2.0.1.0
    Here are the table details :
    DESC Table A
    Name Null Type
    ID               NOT NULL NUMBER
    A1               NOT NULL VARCHAR2(4)
    A2               NOT NULL VARCHAR2(40)
    A3               NOT NULL VARCHAR2(40)
    CREATED_DATE NOT NULL TIMESTAMP(6)
    LAST_MODIFIED_DATE TIMESTAMP(6) DESCribing the tables can help clarify some things, but it's no substitute for posting CREATE TABLE and INSERT statements. With only a description of the table, nobody can re-create the problem or test their ideas. Please post CREATE TABLE and INSERT statements for both tables as they exist before the MERGE. If table b doen't contain any rows before the MERGE, then just say so, but you still need to post a CREATE TABLE statement for both tables, and INSERT statements for table a.
    The objective is to compute the response times : avg (LAST_MODIFIED_DATE - CREATED_DATE), max (LAST_MODIFIED_DATE - CREATED_DATE) and min (LAST_MODIFIED_DATE - CREATED_DATE) grouped by A1 and A2 and store it in table B under AVG_T, MAX_T and MIN_T. Since AVG_T, MAX_T and MIN_T are only used for reporting purposes we have kept it as Varchar (though I think keeping it as timestamp would make more sense). I think a NUMBER would make more sense (the number of minutes, for example), or perhaps an INTERVAL DAY TO SECOND. If you stored a NUMBER, it would be easy to compute averages.
    In table B the times are stored in the format : hh:mm:ss. We don't need milliseconds precision. If you don;'t need milliseconds, then you should use DATE instead of TIMESTAMP. The functions for manipulating DATEs are much better.
    Hence I was calculating is as follows:
    -- Avg Time
    TO_CHAR(TO_DATE(ABS(MOD(TRUNC(AVG(extract(hour FROM (last_modified_date - created_date))*3600 +
    extract( minute FROM (last_modified_date - created_date))*60 +
    extract( second FROM (last_modified_date - created_date)))
    ),86400)),'sssss'),'hh24":"mi":"ss') AS avg_time,
    --Max Time
    extract (hour FROM MAX(last_modified_date - created_date))||':'||extract (minute FROM MAX(last_modified_date - created_date))||':'||TRUNC(extract (second FROM MAX(last_modified_date - created_date))) AS max_time,
    --Min Time
    extract (hour FROM MIN(last_modified_date - created_date))||':'||extract (minute FROM MIN(last_modified_date - created_date))||':'||TRUNC(extract (second FROM MIN(last_modified_date - created_date))) AS min_timeIs this something that has to be done before or after the MERGE?
    Post the complete statement.
    Is this part of a query? Where's the SELECT keyword?
    Is this part of a DML operation? Where's the INSERT, or UPDATE, or MERGE keyword?
    What are the exact results you want from this? Explain how you get those results.
    Is the code above getting the right results? Are you just asking if there's a better way to get the same results?
    You have to explain things very carefully. None of the people who want to help you are familiar with your application, or your needs.
    I just noticed that my reply is horribly formatted - apologies! I'm just getting the hang of it.Whenever you post formatted text (such as query results) on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Select query having count function is returning null

    Hi Everyone,
    Please see the query and help me to get this solved.
    DB version
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - 64bi
    PL/SQL Release 10.2.0.1.0 - Production
    "CORE     10.2.0.1.0     Production"
    TNS for Linux: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - ProductionQUERY
    SELECT COUNT(*) as V_COUNT
          FROM LAB_ORDER_TMPLT_TEST
          WHERE TEST_ID IN
          (SELECT WEST_TEST_ID
                  FROM TEST_CODE_CONVERSION TCC
                  WHERE TCC.EAST_TEST_ID = 2769)
          GROUP BY LAB_ORDER_TMPLT_ID
          HAVING COUNT(*) > 1;
    It's returning null. Is there any way I can get the value as zero instead of null? Please help.Regards,
    BS2012.

    Hi,
    BS2012 wrote:
    Hi Everyone,
    Please see the query and help me to get this solved.
    DB version
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - 64bi
    PL/SQL Release 10.2.0.1.0 - Production
    "CORE     10.2.0.1.0     Production"
    TNS for Linux: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - ProductionQUERY
    SELECT COUNT(*) as V_COUNT
    FROM LAB_ORDER_TMPLT_TEST
    WHERE TEST_ID IN
    (SELECT WEST_TEST_ID
    FROM TEST_CODE_CONVERSION TCC
    WHERE TCC.EAST_TEST_ID = 2769)
    GROUP BY LAB_ORDER_TMPLT_ID
    HAVING COUNT(*) > 1;
    It's returning null.
    Really? COUNT never returns NULL; it always returns 0 or a positive integer.
    Do you mean the query results in "no rows selected"?
    Is there any way I can get the value as zero instead of null? Please help.Do you want a query that will produce the same output as the query above, but will produce a single row containing 0 when the query above does not produce anything? That sounds like a job for an outer join:
    WITH    original_query  AS
           SELECT  COUNT(*) AS v_count
           FROM    lab_order_tmplt_test
           WHERE   test_id IN
                       (   SELECT  west_test_id
                           FROM        test_code_conversion tcc
                           WHERE   tcc.east_test_id = 2769
           GROUP BY  lab_order_tmplt_id
    SELECT     NVL (o.v_count, 0)     AS v_count
    FROM               dual
    LEFT OUTER JOIN  original_query  o  ON  o.v_count > 0
    ;If you'd care to post CREATE TABLE and INSERT statements for the sample data, then I could test this.

  • Problem query inside a function

    Hi,
    I'm trying to create a function that returns me a value after I pass 2 input parameters, a number and a string.
    I've written the function in this way:
    create or replace PACKAGE BODY WORKFLOW_STATISTICS AS
    FUNCTION JOB_MEAN_TIME(workflowID IN NUMBER, object_type IN VARCHAR2) RETURN NUMBER
    IS
    MEAN_TIME NUMBER;
    BEGIN
    DBMS_OUTPUT.PUT_LINE('WORKFLOW_ID: ' || WORKFLOWID);
    select round((avg(b.endtime-b.starttime)/1000), 3) INTO MEAN_TIME
    from DPCTPFSGAIATOOLSWBJOB b, dpctwbjobmanagementinfo d
    where b.dataspectext like '%'||object_type || '%'
    and d.jobid=b.id
    and d.workflowid=workflowID;
    RETURN MEAN_TIME;
    END JOB_MEAN_TIME;
    END WORKFLOW_STATISTICS; The package is compliled correctly but I have 2 problems:
    1) the MEAN_TIME value retrned is not correct
    2) DBMS_OUTPUT.PUT_LINE does not write anything.
    For the point 1 I think I make a mistake when I write this claluse:
    b.dataspectext like '%'||object_type || '%' (e.g I try to obtain '%AstrObservation%' if object_type is "AstroObservation")
    For the point 2 I think I forget to set something.
    Could someone help me?
    Thanks a lot, bye bye.

    Abdujaparov wrote:
    Hi,
    I'm trying to create a function that returns me a value after I pass 2 input parameters, a number and a string.
    I've written the function in this way:
    create or replace PACKAGE BODY WORKFLOW_STATISTICS AS
    FUNCTION JOB_MEAN_TIME(workflowID IN NUMBER, object_type IN VARCHAR2) RETURN NUMBER
    IS
    MEAN_TIME NUMBER;
    BEGIN
    DBMS_OUTPUT.PUT_LINE('WORKFLOW_ID: ' || WORKFLOWID);
    select round((avg(b.endtime-b.starttime)/1000), 3) INTO MEAN_TIME
    from DPCTPFSGAIATOOLSWBJOB b, dpctwbjobmanagementinfo d
    where b.dataspectext like '%'||object_type || '%'
    and d.jobid=b.id
    and d.workflowid=workflowID;
    RETURN MEAN_TIME;
    END JOB_MEAN_TIME;
    END WORKFLOW_STATISTICS; The package is compliled correctly but I have 2 problems:
    1) the MEAN_TIME value retrned is not correct
    2) DBMS_OUTPUT.PUT_LINE does not write anything.
    For the point 1 I think I make a mistake when I write this claluse:
    b.dataspectext like '%'||object_type || '%' (e.g I try to obtain '%AstrObservation%' if object_type is "AstroObservation")
    For the point 2 I think I forget to set something.
    Could someone help me?
    Thanks a lot, bye bye.SQL must be static at compile time.

  • How to reduce functions with simple select query?

    I have a function to identify the root parent of a particular id. I use this in function in select query,which invokes function for every row in table.I need to merge the function inside the query itself.Please suggest  me.
    Function
    CREATE OR REPLACE FUNCTION fnroot(v_id int ) return int as
    v_left int;
    v_right int;
    v-result int;
    begin
    select left,right into v_left,v_right from sam where id=v_id;
    select id into v_result from sam
    where id in (select id from mst m where m.depth=2 )
    and left < v_left and right > v_right;
    return v_result;
    end
    query:
    select fnroot(s.id) from master s;

    Hi,
    Ramin's idea is very good. You must use joins in function as below
    CREATE OR REPLACE FUNCTION fnroot(v_id int ) return int as
        v_result int;
    Begin
    select  s.id into v_result
      from sam s on s.id = v_id
               left join sam s2 on (s2.id in (select id from mst m where m.depth = 2) and s2.left < s.left and s2.right > s.right)
    return v_result;
    End;
    Regards
    Mahir M. Quluzade

  • Database connection(select ,insert query) within javascript function

    Hi ,
    How to write the database connection(insert,delete or select query) within javascript function.Is it possible.Anyone can you help me
    than you

    Hi ,
    How to write the database connection(insert,delete
    ete or select query) within javascript function.Is it
    possible.No

  • How to optimize the select query that is executed in a cursor for loop?

    Hi Friends,
    I have executed the code below and clocked the times for every line of the code using DBMS_PROFILER.
    CREATE OR REPLACE PROCEDURE TEST
    AS
       p_file_id              NUMBER                                   := 151;
       v_shipper_ind          ah_item.shipper_ind%TYPE;
       v_sales_reserve_ind    ah_item.special_sales_reserve_ind%TYPE;
       v_location_indicator   ah_item.exe_location_ind%TYPE;
       CURSOR activity_c
       IS
          SELECT *
            FROM ah_activity_internal
           WHERE status_id = 30
             AND file_id = p_file_id;
    BEGIN
       DBMS_PROFILER.start_profiler ('TEST');
       FOR rec IN activity_c
       LOOP
          SELECT DISTINCT shipper_ind, special_sales_reserve_ind, exe_location_ind
                     INTO v_shipper_ind, v_sales_reserve_ind, v_location_indicator
                     FROM ah_item --464000 rows in this table
                    WHERE item_id_edw IN (
                             SELECT item_id_edw
                               FROM ah_item_xref --700000 rows in this table
                              WHERE item_code_cust = rec.item_code_cust
                                AND facility_num IN (
                                       SELECT facility_code
                                         FROM ah_chain_div_facility --17 rows in this table
                                        WHERE chain_id = ah_internal_data_pkg.get_chain_id (p_file_id)
                                          AND div_id = (SELECT div_id
                                                          FROM ah_div --8 rows in this table
                                                         WHERE division = rec.division)));
       END LOOP;
       DBMS_PROFILER.stop_profiler;
    EXCEPTION
       WHEN NO_DATA_FOUND
       THEN
          NULL;
       WHEN TOO_MANY_ROWS
       THEN
          NULL;
    END TEST;The SELECT query inside the cursor FOR LOOP took 773 seconds.
    I have tried using BULK COLLECT instead of cursor for loop but it did not help.
    When I took out the select query separately and executed with a sample value then it gave the results in a flash of second.
    All the tables have primary key indexes.
    Any ideas what can be done to make this code perform better?
    Thanks,
    Raj.

    As suggested I'd try merging the queries into a single SQL. You could also rewrite your IN clauses as JOINs and see if that helps, e.g.
    SELECT DISTINCT ai.shipper_ind, ai.special_sales_reserve_ind, ai.exe_location_ind
               INTO v_shipper_ind, v_sales_reserve_ind, v_location_indicator
               FROM ah_item ai, ah_item_xref aix, ah_chain_div_facility acdf, ah_div ad
              WHERE ai.item_id_edw = aix.item_id_edw
                AND aix.item_code_cust = rec.item_code_cust
                AND aix.facility_num = acdf.facility_code
                AND acdf.chain_id = ah_internal_data_pkg.get_chain_id (p_file_id)
                AND acdf.div_id = ad.div_id
                AND ad.division = rec.division;ALSO: You are calling ah_internal_data_pkg.get_chain_id (p_file_id) every time. Why not do it outside the loop and just use a variable in the inner query? That will prevent context switching and improve speed.
    Edited by: Dave Hemming on Dec 3, 2008 9:34 AM

  • Dynamic sql with dynamic bulk collection variable

    Hi,
    I am facing the issue while bulk collecting dynamic sql query data into dynamic variable.
    Eg:
    query1:= << dynamic select query>>
    Execute immediate query1 bulk collect into Dynamic_varibale;
    here dynamic_varible is pl/sql table type with 1 column.
    How do i declare "dynamic_variable" here????
    please suggest...

    create type t_id is table of number
    SQL> create type t_id is table of number
      2  /
    Type created.
    SQL> declare
      2
      3   v_tid t_id;
      4   v_results sys_refcursor;
      5
      6   v_employee_id number;
      7   v_name varchar2(100);
      8
      9   v_sql varchar2(1000);
    10
    11
    12  begin
    13   v_tid := t_id(7902,7934);
    14
    15  --
    16
    17
    18   v_sql := 'select empno, ename from scott.emp ' ||CHR(10)
    19           || 'where empno in (select column_value from table(cast(:v_tid as
    t_id)))';
    20
    21   dbms_output.put_line(v_sql);
    22   dbms_output.put_line('----------');
    23
    24   open v_results for v_sql using v_tid;
    25
    26
    27   IF v_results IS NOT NULL
    28     THEN
    29        LOOP
    30           FETCH v_results
    31            INTO v_employee_id, v_name;
    32
    33           EXIT WHEN (v_results%NOTFOUND);
    34           dbms_output.put_line(v_name);
    35        END LOOP;
    36
    37        IF v_results%ISOPEN
    38        THEN
    39           CLOSE v_results;
    40        END IF;
    41    END IF;
    42
    43  end;
    44  /
    select empno, ename from scott.emp
    where empno in (select column_value from
    table(cast(:v_tid as t_id)))
    FORD
    MILLER

  • Bulk collect / forall which collection type?

    Hi I am trying to speed up the query below using bulk collect / forall:
    SELECT h.cust_order_no AS custord, l.shipment_set AS sset
    FROM info.tlp_out_messaging_hdr h, info.tlp_out_messaging_lin l
    WHERE h.message_id = l.message_id
    AND h.contract = '12384'
    AND l.shipment_set IS NOT NULL
    AND h.cust_order_no IS NOT NULL
    GROUP BY h.cust_order_no, l.shipment_set
    I would like to extract the 2 fields selected above into a new table as quickly as possible, but I’m fairly new to Oracle and I’m finding it difficult to sort out the best way to do it. The query below does not work (no doubt there are numerous issues) but hopefully it is sufficiently developed to shows the sort of thing I am trying to achieve:
    DECLARE
    TYPE xcustord IS TABLE OF info.tlp_out_messaging_hdr.cust_order_no%TYPE;
    TYPE xsset IS TABLE OF info.tlp_out_messaging_lin.shipment_set%TYPE;
    TYPE xarray IS TABLE OF tp_a1_tab%rowtype INDEX BY BINARY_INTEGER;
    v_xarray xarray;
    v_xcustord xcustord;
    v_xsset xsset;
    CURSOR cur IS
    SELECT h.cust_order_no AS custord, l.shipment_set AS sset
    FROM info.tlp_out_messaging_hdr h, info.tlp_out_messaging_lin l
    WHERE h.message_id = l.message_id
    AND h.contract = '1111'
    AND l.shipment_set IS NOT NULL
    AND h.cust_order_no IS NOT NULL;
    BEGIN
    OPEN cur;
    LOOP
    FETCH cur
    BULK COLLECT INTO v_xarray LIMIT 10000;
    EXIT WHEN v_xcustord.COUNT() = 0;
    FORALL i IN 1 .. v_xarray.COUNT
    INSERT INTO TP_A1_TAB (cust_order_no, shipment_set)
    VALUES (v_xarray(i).cust_order_no,v_xarray(i).shipment_set);
    commit;
    END LOOP;
    CLOSE cur;
    END;
    I am running on Oracle 9i release 2.

    Well I suppose I can share the whole query as it stands for context and information (see below).
    This is a very ugly piece of code that I am trying to improve. The advantage it has currently is
    that it works, the disadvantage it has is that it's very slow. My thoughts were that bulk collect
    and forall might be useful tools here as part of the re-write hence my original question, but perhaps not.
    So on a more general note any advice on how best speed up this code would be welcome:
    CREATE OR REPLACE VIEW DLP_TEST AS
    WITH aa AS
    (SELECT h.cust_order_no AS c_ref,l.shipment_set AS shipset,
    l.line_id, h.message_id, l.message_line_no,
    l.vendor_part_no AS part, l.rqst_quantity AS rqst_qty, l.quantity AS qty,
    l.status AS status, h.rowversion AS allocation_date
    FROM info.tlp_in_messaging_hdr h
    LEFT JOIN  info.tlp_in_messaging_lin l
    ON h.message_id = l.message_id
    WHERE h.contract = '12384'
    AND h.cust_order_no IS NOT NULL
    UNION ALL
    SELECT ho.cust_order_no AS c_ref, lo.shipment_set AS shipset,
    lo.line_id, ho.message_id, lo.message_line_no,
    lo.vendor_part_no AS part,lo.rqst_quantity AS rqst_qty, lo.quantity AS qty,
    lo.status AS status, ho.rowversion AS allocation_date
    FROM info.tlp_out_messaging_hdr ho, info.tlp_out_messaging_lin lo
    WHERE ho.message_id = lo.message_id
    AND ho.contract = '12384'
    AND ho.cust_order_no IS NOT NULL),
    a1 AS
    (SELECT h.cust_order_no AS custord, l.shipment_set AS sset
    FROM info.tlp_out_messaging_hdr h, info.tlp_out_messaging_lin l
    WHERE h.message_id = l.message_id
    AND h.contract = '12384'
    AND l.shipment_set IS NOT NULL
    AND h.cust_order_no IS NOT NULL
    GROUP BY h.cust_order_no, l.shipment_set),
    a2 AS
    (SELECT ho.cust_order_no AS c_ref, lo.shipment_set AS shipset
    FROM info.tlp_out_messaging_hdr ho, info.tlp_out_messaging_lin lo
    WHERE ho.message_id = lo.message_id
    AND ho.contract = '12384'
    AND ho.message_type = '3B13'
    AND lo.shipment_set IS NOT NULL
    GROUP BY ho.cust_order_no, lo.shipment_set),
    a3 AS
    (SELECT a1.custord, a1.sset, CONCAT('SHIPSET',a1.sset) AS ssset
    FROM a1
    LEFT OUTER JOIN a2
    ON a1.custord = a2.c_ref AND a1.sset = a2.shipset
    WHERE a2.c_ref IS NULL),
    bb AS
    (SELECT so.contract, so.order_no, sr.service_request_no AS sr_no, sr.reference_no,
    substr(sr.part_no,8) AS shipset,
    substr(note_text,1,instr(note_text,'.',1,1)-1) AS Major_line,
    note_text AS CISCO_line,ma.part_no,
    (Select TO_DATE(TO_CHAR(TO_DATE(d.objversion,'YYYYMMDDHH24MISS'),'YYYY-MM-DD HH24:MI:SS'),'YYYY-MM-DD HH24:MI:SS')
    FROM ifsapp.document_text d WHERE so.note_id = d.note_id AND so.contract = '12384') AS Print_Date,
    ma.note_text
    FROM (ifsapp.service_request sr
    LEFT OUTER JOIN ifsapp.work_order_shop_ord ws
    ON sr.service_request_no = ws.wo_no
    LEFT OUTER JOIN ifsapp.shop_ord so
    ON ws.order_no = so.order_no)
    LEFT OUTER JOIN ifsapp.customer_order co
    ON sr.reference_no = co.cust_ref
    LEFT OUTER JOIN ifsapp.shop_material_alloc ma
    ON so.order_no = ma.order_no
    JOIN a3
    ON a3.custord = sr.reference_no AND a3.sset = substr(sr.part_no,8)
    WHERE sr.part_contract = '12384'
    AND so.contract = '12384'
    AND co.contract = '12384'
    AND sr.reference_no IS NOT NULL
    AND ma.part_no NOT LIKE 'SHIPSET%'),
    cc AS
    (SELECT 
    bb.reference_no,
    bb.shipset,
    bb.order_no,
    bb.cisco_line,
    aa.message_id,
    aa.allocation_date,
    row_number() over(PARTITION BY bb.reference_no, bb.shipset, aa.allocation_date
    ORDER BY bb.reference_no, bb.shipset, aa.allocation_date, aa.message_id DESC) AS selector
    FROM bb
    LEFT OUTER JOIN aa
    ON  bb.reference_no = aa.c_ref AND bb.shipset = aa.shipset
    WHERE aa.allocation_date <= bb.print_date
    OR aa.allocation_date IS NULL
    OR bb.print_date IS NULL),
    dd AS
    (SELECT
    MAX(reference_no) AS reference_no,
    MAX(shipset) AS shipset,
    order_no,
    MAX(allocation_date) AS allocation_date
    FROM cc
    WHERE selector = 1                                   
    GROUP BY order_no, selector),
    ee AS
    (SELECT
    smx.order_no,
    SUM(smx.qty_assigned) AS total_allocated,
    SUM(smx.qty_issued) AS total_issued,
    SUM(smx.qty_required) AS total_required
    FROM ifsapp.shop_material_alloc smx
    WHERE smx.contract = '12384'
    AND smx.part_no NOT LIKE 'SHIPSET%'
    GROUP BY smx.order_no),
    ff AS
    (SELECT
    dd.reference_no,
    dd.shipset,
    dd.order_no,
    MAX(allocation_date) AS last_allocation,
    MAX(ee.total_allocated) AS total_allocated,
    MAX(ee.total_issued) AS total_issued,
    MAX(ee.total_required) AS total_required
    FROM dd
    LEFT OUTER JOIN ee
    ON dd.order_no = ee.order_no
    GROUP BY dd.reference_no, dd.shipset, dd.order_no),
    base AS
    (SELECT x.order_no, x.part_no, z.rel_no, MIN(x.dated) AS dated, MIN(y.cust_ref) AS cust_ref, MIN(z.line_no) AS line_no,
    MIN(y.state) AS state, MIN(y.contract) AS contract, MIN(z.demand_order_ref1) AS demand_order_ref1
    FROM ifsapp.inventory_transaction_hist x, ifsapp.customer_order y, ifsapp.customer_order_line z
    WHERE x.contract = '12384'
    AND x.order_no = y.order_no
    AND y.order_no = z.order_no
    AND x.transaction = 'REP-OESHIP'
    AND x.part_no = z.part_no
    AND TRUNC(x.dated) >= SYSDATE - 8
    GROUP BY x.order_no, x.part_no, z.rel_no)
    SELECT
    DISTINCT
    bb.contract,
    bb.order_no,
    bb.sr_no,
    CAST('-' AS varchar2(40)) AS Usr,
    CAST('-' AS varchar2(40)) AS Name,
    CAST('01' AS number) AS Operation,
    CAST('Last Reservation' AS varchar2(40)) AS Action,
    CAST('-' AS varchar2(40)) AS Workcenter,
    CAST('-' AS varchar2(40)) AS Next_Workcenter_no,
    CAST('Print SO' AS varchar2(40)) AS Next_WC_Description,
    ff.total_allocated,
    ff.total_issued,
    ff.total_required,
    ff.shipset,
    ff.last_allocation AS Action_date,
    ff.reference_no
    FROM ff
    LEFT OUTER JOIN bb
    ON bb.order_no = ff.order_no
    WHERE bb.order_no IS NOT NULL
    UNION ALL
    SELECT
    c.contract AS Site, c.order_no AS Shop_Order, b.wo_no AS SR_No,
    CAST('-' AS varchar2(40)) AS UserID,
    CAST('-' AS varchar2(40)) AS User_Name,
    CAST('02' AS number) AS Operation,
    CAST('SO Printed' AS varchar2(40)) AS Action,
    CAST('SOPRINT' AS varchar2(40)) AS Workcenter,
    CAST('PKRPT' AS varchar2(40)) AS Next_Workcenter_no,
    CAST('Pickreport' AS varchar2(40)) AS Next_WC_Description,
    CAST('0' AS number) AS Total_Allocated,
    CAST('0' AS number) AS Total_Issued,
    CAST('0' AS number) AS Total_Required,
    e.part_no AS Ship_Set,
    TO_DATE(TO_CHAR(TO_DATE(d.objversion,'YYYYMMDDHH24MISS'),'YYYY-MM-DD HH24:MI:SS'),'YYYY-MM-DD HH24:MI:SS')AS Action_Date,
    f.cust_ref AS cust_ref
    FROM ifsapp.shop_ord c
    LEFT OUTER JOIN ifsapp.work_order_shop_ord b
    ON b.order_no = c.order_no
    LEFT OUTER JOIN ifsapp.document_text d
    ON d.note_id = c.note_id
    LEFT OUTER JOIN ifsapp.customer_order_line e
    ON e.demand_order_ref1 = TRIM(to_char(b.wo_no))
    LEFT OUTER JOIN ifsapp.customer_order f
    ON f.order_no = e.order_no
    JOIN a3
    ON a3.custord = f.cust_ref AND a3.ssset = e.part_no
    WHERE c.contract = '12384'
    AND e.contract = '12384'
    AND d.objversion IS NOT NULL
    UNION ALL
    SELECT
    a.site AS Site, a.order_no AS Shop_Order, b.wo_no AS SR_No, a.userid AS UserID,
    a.user_name AS Name, a.operation_no AS Operation, a.action AS Action,
    a.workcenter_no AS Workcenter, a.next_work_center_no AS Next_Workcenter_no,
    (SELECT d.description  FROM ifsapp.work_center d WHERE a.next_work_center_no = d.work_center_no AND a.site = d.contract)
    AS Next_WC_Description,
    CAST('0' AS number) AS Total_Allocated,
    CAST('0' AS number) AS Total_Issued,
    CAST('0' AS number) AS Total_Required,
    e.part_no AS Ship_set,
    a.action_date AS Action_Date, f.cust_ref AS cust_ref
    FROM ifsapp.shop_ord c
    LEFT OUTER JOIN ifsapp.work_order_shop_ord b
    ON b.order_no = c.order_no
    LEFT OUTER JOIN ifsapp.customer_order_line e
    ON e.demand_order_ref1 = to_char(b.wo_no)
    LEFT OUTER JOIN ifsapp.customer_order f
    ON f.order_no = e.order_no
    LEFT OUTER JOIN info.tp_hvt_so_op_hist a
    ON a.order_no = c.order_no
    JOIN a3
    ON a3.custord = f.cust_ref AND a3.ssset = e.part_no
    WHERE a.site = '12384'
    AND c.contract = '12384'
    AND e.contract = '12384'
    AND f.contract = '12384'
    UNION ALL
    SELECT so.contract AS Site, so.order_no AS Shop_Order_No, sr.service_request_no AS SR_No,
    CAST('-' AS varchar2(40)) AS "User",
    CAST('-' AS varchar2(40)) AS "Name",
    CAST('999' AS number) AS "Operation",
    CAST('Shipped' AS varchar2(40)) AS "Action",
    CAST('SHIP' AS varchar2(40)) AS "Workcenter",
    CAST('-' AS varchar2(40)) AS "Next_Workcenter_no",
    CAST('-' AS varchar2(40)) AS "Next_WC_Description",
    CAST('0' AS number) AS Total_Allocated,
    CAST('0' AS number) AS Total_Issued,
    CAST('0' AS number) AS Total_Required,
    so.part_no AS ship_set, base.dated AS Action_Date,
    sr.reference_no AS CUST_REF
    FROM base
    LEFT OUTER JOIN ifsapp.service_request sr
    ON base.demand_order_ref1 = sr.service_request_no
    LEFT OUTER JOIN ifsapp.work_order_shop_ord ws
    ON sr.service_request_no = ws.wo_no
    LEFT OUTER JOIN ifsapp.shop_ord so
    ON ws.order_no = so.order_no
    WHERE base.contract = '12384';

  • Bulk collect with Nested loops

    Hi I've a requirement like this
    I need to pull request nos from table a(Master table)
    For every request no I need to pull request details from table b(Detail Table)
    For every request no I need to pull contact details from table c
    For every request no I need to pull customer data table d and I need to create a flat file with that data so I'm using utl_file in normal query criterion because of nested loops it's taking lot of time so I want to use bulk collect with dynamic query option:
    Sample code
    =======
    create or replace procedure test(region varchar2) as
    type tablea_request_typ is table of varchar2(10);
    tablea_data tablea_request_typ;
    type tableb_request_typ is table of varchar2(1000);
    tableb_data tableb_request_typ;
    type tablec_request_typ is table of varchar2(1000);
    tablec_data tablec_request_typ;
    type tabled_request_typ is table of varchar2(1000);
    tabled_data tabled_request_typ;
    stmta varchar2(32000);
    stmtb varchar2(32000);
    stmtc varchar2(32000);
    stmtd varchar2(32000);
    rcura SYS_REFCURSOR;
    rcurb SYS_REFCURSOR;
    rcurc SYS_REFCURSOR;
    rcurd SYS_REFCURSOR;
    begin
    stmta:='select  request_no from tablea where :region'||'='NE';
    stmtb:='select  request_no||request_detail1||request_detail2 stringb  from table b where :region'||'='NE';
    stmtc:='select contact1||contact2||contact3||contact4  stringc from table c where :region'||'='NE';
    stmtd:='select customer1||customer2||customer3||customer4  stringd  from table c where :region'||'='NE';
    OPEN rcura for stmta;
      LOOP
      FETCH rcura BULK COLLECT INTO request_no
      LIMIT 1000;
      FOR  f in 1..request_no.count
    LOOP
    --Tableb
        OPEN rcurb for stmtb USING substr(request_no(f),1,14);
      LOOP
      FETCH rcurb BULK COLLECT INTO tableb_data
    for i in 1..tableb_data.count
    LOOP
    utl_file(...,tableb_data(i));
    END LOOP;
        EXIT WHEN rcurb%NOTFOUND;
      END LOOP;
    -- Tablec
    OPEN rcurc for stmtc USING substr(request_no(f),1,14);
      LOOP
      FETCH rcurb BULK COLLECT INTO tablec_data
    for i in 1..tablec_data.count
    LOOP
    utl_file(...,tablec_data(i));
    END LOOP;
        EXIT WHEN rcurc%NOTFOUND;
      END LOOP;
    -- Tabled
    OPEN rcurd for stmtd USING substr(request_no(f),1,14);
      LOOP
      FETCH rcurd BULK COLLECT INTO tabled_data
    for i in 1..tabled_data.count
    LOOP
    utl_file(...,tabled_data(i));
    END LOOP;
        EXIT WHEN rcurd%NOTFOUND;
      END LOOP;
      END LOOP;
        EXIT WHEN rcura%NOTFOUND;
      END LOOP;
    exception
    when other then
    dbms_output.put_line(sqlerrm);
    end;I 'm using code mentioned above but request nos are repeating as if it's an infinete loop ?for ex if request no is 222 It should run once but here it's running more than once?
    How to pass bind parameters say in my case region?
    Are there any alternate solutions to run it faster apart from using bulk collect?
    Right now I'm using explicit cursor with for loop which is taking lot of time ?so is this better sol?
    Thanks,
    Mahender
    Edited by: BluShadow on 24-Aug-2011 08:52
    added {noformat}{noformat} tags. Please read {message:id=9360002} to learn to format your code/data yourself.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

        Use Parameterized cursor :
    CREATE OR REPLACE PROCEDURE test(region varchar2)
    AS
      type tablea_request_typ is table of varchar2(10);
      type tableb_request_typ is table of varchar2(1000); 
      type tablec_request_typ is table of varchar2(1000);
      type tabled_request_typ is table of varchar2(1000);
      tablea_data tablea_request_typ;
      tableb_data tableb_request_typ;
      tablec_data tablec_request_typ;
      tabled_data tabled_request_typ;
       CURSOR rcura(v_region  VARCHAR2(100))
       IS
       select  request_no from tablea where region = v_region;
       CURSOR rcurb(v_input  VARCHAR2(100))
       IS
       select  request_no||request_detail1||request_detail2 stringb  from table b where request_num = v_input;
       CURSOR rcurc(v_input  VARCHAR2(100))
       IS
       select  select contact1||contact2||contact3||contact4  stringc from table c where request_num = v_input;
       CURSOR rcurd(v_input  VARCHAR2(100))
       IS
       select  select customer1||customer2||customer3||customer4  stringd  from table c where request_num = v_input;
    BEGIN
    OPEN rcura('NE');
    LOOP
        FETCH rcura BULK COLLECT INTO request_no  LIMIT 1000;
        FOR  f in 1..request_no.count
        LOOP
           --Tableb
           OPEN rcurb(substr(request_no(f),1,14));
           LOOP
              FETCH rcurb BULK COLLECT INTO tableb_data
              for i in 1..tableb_data.count
              LOOP
                  utl_file(...,tableb_data(i));
              END LOOP;
              EXIT WHEN rcurb%NOTFOUND;
           END LOOP;
           -- Tablec
           OPEN rcurc (substr(request_no(f),1,14));
           LOOP
              FETCH rcurb BULK COLLECT INTO tablec_data
              for i in 1..tablec_data.count
              LOOP
                 utl_file(...,tablec_data(i));
              END LOOP;
              EXIT WHEN rcurc%NOTFOUND;
           END LOOP;
           -- Tabled
           OPEN rcurd ( substr(request_no(f),1,14) );
           LOOP
              FETCH rcurd BULK COLLECT INTO tabled_data
              for i in 1..tabled_data.count
              LOOP
               utl_file(...,tabled_data(i));
              END LOOP;
              EXIT WHEN rcurd%NOTFOUND;
           END LOOP;
      END LOOP;
    EXIT WHEN rcura%NOTFOUND;
    END LOOP;
    EXCEPTION
    WHEN OTHERS THEN
       dbms_output.put_line(dbms_utility.format_error_backtrace);
    END;
    /Hope this helps. If not, post your table structures...

  • Index in Query inside Stored procedure

    How to put a index on Select query inside a stored procedure.Please help me on below to write a index
    Coalesce ((select sum (ICD.mAmount)
    from ItemCommonData ICD (Index(PK_ItemCommonData))
    Join ItemsInBundle IIBun on
    (ICD.iBundleDocId = IIBun.iBundleDocId) and
    (ICD.iDocId = IIBun.iDocId)
    Join ItemsInBlock IIB (Index(ItemsInBlockbyBlockDoc)) on
    (ICD.iDocId = IIB.iDocId)
    where (Bundles.iDocId = ICD.iBundleDocId
    and IIBun.fDeleted = False
    and IIB.iBlockId = iBlockId)),

    Are you migrating to Oracle SQL and PL/SQL?
    Anyway, you don't define an Index on the fly in Oracle. You create them ahead of time on the table. You can use hints to manipulate the query into using a certain execution path.

Maybe you are looking for

  • Spry Validation: Strong Password

    Hi Chaps, I'm looking for a bit of Spry Script to validate a user password input on a sign_up.php script. I can validate the input for 'No Special Characters' and the 'Number of Min/Max Characters': <script> function myValidation(value) {    return /

  • Using data from another farm

    Hello, I would like to populate a list column with data (Lot #'s) from a list on another sp farm updating frequently. I want to use the column as a lookup to the Lot #'s. Possible? Authentication? Thank you, Andrea  Andrea

  • Final cut x import window freezes

    Import from camera works, but FCP import window freezes.  6-core Mac Pro, plenty of RAM, fast drives, worked before.

  • Problems syncing iTunes 10.5 with Photoshop Elements

    Hi all, I've used the "Sync Photos from Photoshop Elements" option in iTunes for a long time to sync photos with my iPhone and iPad. Something's gone wrong with this since I upgraded to iTunes 10.5. I use Photoshop Elements 7. For the iPhone, I sync

  • Can I recreate my Timemachine Backups from my old MacBook on a new MacBook Pro?

    My MacBook (white, 6.1, late 2009, 2,26 GHz, Intel Core 2 Duo, OS X 10.9.3) has a major problem with frequent crashes after some minutes. I have a MacBook pro 13" and intend to try to move all contents (pictures, music, mail and everything else of im