Fetch API cursor

Hi, 
The sql service is reporting the following query running more 100k execution per minutes-  fetch api_cursor 000000018.
How can I diagnose, which queries are being requested from my database. 
i tried executing the following query:
SELECT c.session_id, c.properties, c.creation_time, c.is_open, t.text
FROM sys.dm_exec_cursors (53) c
CROSS APPLY sys.dm_exec_sql_text (c.sql_handle) t
I get the following response error from sql - The user does not have permission to perform this action.
any further guide would be very helpful. Thanks

Hunting down the origins of FETCH API_CURSOR
http://www.sqlskills.com/blogs/joe/hunting-down-the-origins-of-fetch-api_cursor-and-sp_cursorfetch/
http://blog.sqlauthority.com/2015/01/10/sql-server-what-is-the-query-used-in-sp_cursorfetch-and-fetch-api_cursor/
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/c25eecce-5ae5-4620-950a-485ddf4fddc8/fetch-apicursor
To use dm_exec_sql_text you need VIEW SERVER STATE permissions. 
See http://msdn.microsoft.com/en-us/library/ms181929.aspx?ppud=4
Even if you are thinking to use DBCC inputbuffer
Permissions default to members of the sysadmin fixed server role only, who can see any SPID. Other users can see any SPID they own. 

Similar Messages

  • Can't insert recors fetched by cursor in the table

    HI
    i am fetching records from my table total_budget.All the fetched records are displayed in a tabular data block(data block name is forecast_result).Now i want to insert these record fetched by cursor in my table forecast_resul which is empty.how can i do it.I am sending the code if any one can help............
    When i execute this code it give me error unable to insert(FRM-40508) .I have carefully checked table columns names and their data types.All r fine but i dont know y it is not working.Here is the code
    DECLARE
    cursor c1 IS
    SELECT ministry_id,fiscal_year ,t_amount
    FROM total_budget
    WHERE ministry_id=:global.var11 AND (fiscal_year BETWEEN :syear and :eyear);
    BEGIN
    T_XSUMX := 0;
         OPEN C1;
         X:=1;
         SUMX := 0; SUMY := 0; SUMXY:=0; SUMX2 := 0;
         go_block('forecast_result');
         first_record;
         LOOP
              FETCH C1 INTO Y1,Y2,Y;
              EXIT WHEN C1%NOTFOUND;
              SUMY := SUMY +Y;
              XY := X*Y;
              X2 := X*X;
              SUMX := SUMX + X;
    SUMXY := SUMXY + XY;
              SUMX2 := SUMX2 + X2;
                   :forecast_result.ministry_id:=Y1;
                   :forecast_result.fiscal_year:=Y2;
              :forecast_result.t_amount:=Y;
         NEXT_RECORD;
              X := X + 1;
         END LOOP;
         close C1;
    z:=X-2;
         X_BAR := z;
         X := z+1;
         T_XSUMX := X * SUMX;
         T_SUMY := SUMY * SUMX;
         T_SUMX := SUMX * SUMX;
         T_SUMXY := SUMXY * X;
         T_SUMX2 := SUMX2 * X;
         R1 := T_SUMY - T_SUMXY;
         R2 := T_SUMX - T_SUMX2;
         B := ROUND(R1/R2,1);
         A := ROUND((T_SUMXY -(T_SUMX2*B))/T_XSUMX,1);
         Y_BAR := A+(B*X_BAR);
    :forecast_result.ministry_id:=Y1;
    :forecast_result.fiscal_year:=Y2;
    :forecast_result.t_amount:=Y_BAR;
    next_record;
         insert into forecast_result
         values(:forecast_result.ministry_id,:forecast_result.fiscal_year,:forecast_result.t_amount);
         commit;
    END;
    Can anyone tell me wat i am doing wrong
    looking for instant reply
    nida

    Hi alma,
    Plz u dnt wrt babytalk rr SMS-language -> mi! Becoz mi don lejk dat.
    I suppose that your data block "forecast_result" are based on the table of the same name. Otherwise this may be the cause of some of your trouble.
    Your code would properly work better like this:
    DECLARE
      X NUMBER(38);
      SUMX NUMBER(38);
      SUMY NUMBER(38);
      Y NUMBER(38) ;
      Y1 varchar2(10);
      Y2 varchar2(10);
      X2 NUMBER(38);
      XY NUMBER(38);
      SUMXY NUMBER(38);
      SUMX2 NUMBER(38);
      X_BAR NUMBER(38);
      Y_BAR NUMBER(38);
      T_SUMY NUMBER(38);
      T_SUMX NUMBER(38);
      T_SUMXY NUMBER(38);
      T_SUMX2 NUMBER(38);
      T_XSUMX NUMBER(38);
      R1 NUMBER(38);
      R2 NUMBER(38);
      A NUMBER(38);
      z number(38);
      B NUMBER(38);
      final number(38);
      -- Just curious, where does :syear and :eyear come from ??
      cursor c1 IS
       SELECT ministry_id, fiscal_year, t_amount
        FROM total_budget
       WHERE ministry_id=:global.var11
         AND (fiscal_year BETWEEN :syear and :eyear);
    BEGIN
      T_XSUMX := 0;
      X:=1;
      SUMX := 0;
      SUMY := 0;
      SUMXY:=0;
      SUMX2 := 0;
      go_block('forecast_result');
      -- If you're making this dynamically, then clear the block to start with.
      clear_block(NO_COMMIT);
      first_record;
      OPEN C1;
      LOOP
        FETCH C1 INTO Y1, Y2, Y;
        EXIT WHEN C1%NOTFOUND;
        SUMY := SUMY + Y;
        XY := X*Y;
        X2 := X*X;
        SUMX := SUMX + X;
        SUMXY := SUMXY + XY;
        SUMX2 := SUMX2 + X2;
        :forecast_result.ministry_id := Y1;
        :forecast_result.fiscal_year := Y2;
        :forecast_result.t_amount := Y;
        -- NO, this will not work. You have to CREATE the record. You only get the
        -- first record for "free". Next_Record moves to allready existing records.
        -- NEXT_RECORD;
        Create_Record;
        X := X + 1;
      END LOOP;
      close C1;
      z := X - 2;
      X_BAR := z;
      X := z + 1;
      T_XSUMX := X * SUMX;
      T_SUMY := SUMY * SUMX;
      T_SUMX := SUMX * SUMX;
      T_SUMXY := SUMXY * X;
      T_SUMX2 := SUMX2 * X;
      R1 := T_SUMY - T_SUMXY;
      R2 := T_SUMX - T_SUMX2;
      B := ROUND(R1/R2,1);
      A := ROUND((T_SUMXY -(T_SUMX2*B))/T_XSUMX,1);
      Y_BAR := A+(B*X_BAR);
      -- What are you doing here ?? This is weird. The population of the records are done in
      -- the loop ! You don't have to add anything here.
      -- :forecast_result.ministry_id:=Y1;
      -- :forecast_result.fiscal_year:=Y2;
      -- :forecast_result.t_amount:=Y_BAR;
      -- Since your data block (hopefully) are based on the table of the same name, you DON'T
      -- need to do this. You just have to press the commit button (or F10 or the floppy disk
      -- icon or what-ever).
      -- insert into forecast_result
      -- values(:forecast_result.ministry_id,:forecast_result.fiscal_year,:forecast_result.t_amount);
      -- commit;
    END;

  • Fetch next cursor/ invalid database interruption

    Hi Experts,
    I would appreciate your help for the following problem:
    I am trying to develope something like that:
    OPEN CURSOR ... WITH HOLD
    loop at ...
             FETCH ... PACKAGE SIZE ... into lt_names
             insert table ZZ_XXXX ... from lt_names
             commit work
    endloop.
    in the second loop, the FETCH dumps raising the runtime error "Invalid interruption of a database selection"
    Runtime Error          DBIF_RSQL_INVALID_CURSOR
    Exception              CX_SY_OPEN_SQL_DB      
    The cursor is opened "with hold".
    Does anybody know, why does it dump?
    Cheers
    marmsg

    Hi Thomas,
    I have four entires in a custom z-table. During FETCH Statements, I use, PACKET SIZE, of 2.
    Rough code is as follows:
    OPEN CURSOR WITH HOLD w_dbcur1 FOR
    SELECT * FROM ztable.
    WHILE sy-subrc = 0.
    FETCH NEXT CURSOR w_dbcur1 INTO TABLE i_notes PACKAGE SIZE p_pack. "Here packet size is of 2
    IF sy-subrc = 0.
    Calling some X BAPI Function module.
    Calling BAPI_TRANSACTION_COMMIT Function module.
    ENDIF.
    ENDWHILE.
    CLOSE CURSOR w_dbcur1.
    Here the problem is, if I give packet size as 30,000, then program is working fine. If I am giving packet size as 2, which less than 4 entries in the table, The program dumps either at first execution of FETCH NEXT CURSOR statement or at the second time of FETCH NEXT CURSOR. Can you provide exact solution for this, and not the links please. Rewards will be provided.
    Thanks,
    Vijayanand.

  • Fetch Next Cursor Short Dumps

    Hello All,
       I have the following code which short dumps after losing its cursor position. 
    OPEN CURSOR WITH HOLD dbcur FOR
          select * from ekpo where bukrs in s_bukrs2.
          do.
              FETCH NEXT CURSOR dbcur INTO table iekpo package size pkgsize.
              if sy-subrc <> 0.
                 close cursor dbcur.
                 exit.
              else.
                  perform ouput_to_text_file.
                  refresh: iekpo.
               endif.
          enddo.
    I have millions of records to be extracted and  simple select to an internal table causes memory problems.  Thus I need to extract a chunk of records write them to a text file, then get the next chunk. 
    Any suggestions?
    Thank you,
    Jerry

    GUI Download probably causes problem, writing to a dataset on app server might not cause the problem, maybe you want to try.
    Regarding the select, here is some pseudo code outlining what I mean:
    clear wa_ekpo.
    do.
      select * from ekpo into table lt_ekpo up to 10,000 rows
          where ebeln > wa_ekpo-ebeln or ( ebeln = wa_ekpo-ebeln and ebelp > wa_ekpo-ebelp )
          order by primary key.
      if sy-subrc ne 0.
        exit.
      endif.
      download lt_ekpo (appending to existing file)
      l_lines = lines( lt_ekpo ).
      read table lt_ekpo into wa_ekpo index l_lines.
    enddo.
    Will run for a while, but should not dump out
    Thomas

  • Fetching from cursor

    Hello all.
    How can i enforce the sql+ start fetching first cursor field by
    one field intervals?
    My sql+ starts fetch from the second item by 2 records intervals,
    so the 4th record is the next one to fetched after the second.
    best regards
    yosi sarid.

    Hi,
    could you please show us the where clause of the cursor?
    I think you are missing something.
    Another fault in your Code is the x_commit_count.
    You increment it every time, but you never set it to zero again. So after 100 inserts, it commits after each loopstep.
    Is this what you want???
    DECLARE
    CURSOR c_cursor IS SELECT * FROM TABLE_A@REMOTE, TABLE_B@REMOTE WHERE...
    x_commit_count NUMBER := 0;
    BEGIN
    FOR r_record IN c_cursor LOOP
    INSERT INTO LOCAL_TABLE;
    x_commit_count := x_commit_count + 1;
    IF x_commit_count >= 100 THEN
    COMMIT;
    ELSE
    NULL;
    END IF;
    END LOOP;
    END;
    HTH
    Detlev

  • How to fetch from cursor into plsql collection

    Dear Friends,
    I am trying to understand PLSQL collections. I am trying with the following example.
    CREATE OR REPLACE TYPE emp_obj AS OBJECT
    (     empname          VARCHAR2(100),     empjob          VARCHAR2(50),     empsal          NUMBER);
    CREATE OR REPLACE TYPE emp_tbl IS TABLE OF emp_obj;
    CREATE OR REPLACE PACKAGE eg_collection AS
    -- Delcare ref cursor
    TYPE rc IS REF CURSOR;
    -- Procedure
    PROCEDURE eg_collection_proc (out_result OUT rc);
    END;
    CREATE OR REPLACE PACKAGE BODY eg_collection AS
    PROCEDURE eg_collection_proc( out_result OUT rc) AS
    emp_tdt     emp_tbl := emp_tbl(emp_obj('oracle','DBA',100));
    CURSOR c2 IS SELECT ename,job,sal FROM emp WHERE sal > 2000;
    -- Declare a record type to hold the records from cursor and then pass to the collection
    emp_rec emp_obj;
    BEGIN
         OPEN c2;
         LOOP FETCH c1 INTO emp_rec;
              EXIT WHEN c1%NOTFOUND;
              emp_tdt.extend;
    emp_tdt(emp_tdt.count) := emp_rec;
         END LOOP;
         CLOSE c2;
    OPEN out_result FOR SELECT * FROM TABLE(CAST(emp_tdt AS emp_tbl));
    END eg_collection_proc;
    END eg_collection;
    Executing the proc
    variable r refcursor;
    exec eg_collection.eg_collection_proc(:r);
    print r;
    But I am getting compilation error type mismatch found at emp_rec between fetch cursor into variable

    I am trying to understand PLSQL collections. I dont why the code is not working
    SQL> CREATE OR REPLACE TYPE emp_obj AS OBJECT
    2 (
    3      empname          VARCHAR2(100),
    4      empjob          VARCHAR2(50),
    5      empsal          NUMBER
    6 )
    7 /
    Type created.
    SQL> CREATE OR REPLACE TYPE emp_tbl IS TABLE OF emp_obj
    2 /
    Type created.
    SQL> DECLARE
    2      emp_tdt emp_tbl := emp_tbl ();
    3 BEGIN
    4
    5      emp_tdt.extend;
    6      SELECT emp_obj(ename, job, sal) BULK COLLECT INTO emp_tdt
    7      FROM emp WHERE sal < 4000;
    8
    9      DBMS_OUTPUT.PUT_LINE ('The total count is ' || emp_tdt.count);
    10
    11      emp_tdt.extend;
    12      SELECT ename, job, sal INTO emp_tdt(1).empname, emp_tdt(1).empjob, emp_tdt(1).empsal
    13      FROM emp WHERE empno = 7900;
    14
    15      DBMS_OUTPUT.PUT_LINE ('The total count is ' || emp_tdt.count);
    16
    17 END;
    18 /
    The total count is 13
    The total count is 14
    PL/SQL procedure successfully completed.
    SQL> DECLARE
    2      emp_tdt emp_tbl := emp_tbl ();
    3 BEGIN
    4
    5      emp_tdt.extend;
    6      SELECT ename, job, sal INTO emp_tdt(1).empname, emp_tdt(1).empjob, emp_tdt(1).empsal
    7      FROM emp WHERE empno = 7900;
    8
    9      DBMS_OUTPUT.PUT_LINE ('The total count is ' || emp_tdt.count);
    10
    11      emp_tdt.extend;
    12      SELECT emp_obj(ename, job, sal) BULK COLLECT INTO emp_tdt
    13      FROM emp WHERE sal < 4000;
    14
    15      DBMS_OUTPUT.PUT_LINE ('The total count is ' || emp_tdt.count);
    16 END;
    17 /
    DECLARE
    ERROR at line 1:
    ORA-06530: Reference to uninitialized composite
    ORA-06512: at line 6

  • Dynamic Column Name while Fetching from Cursor?

    Scenario:
    I have a table having 5 Column C01,C02,C03,C04,C05....... now i have
    a record type variable att_rec. One first fetch the first record
    fetch into att_rec and i can access column like
    att_rec.C01,att_rec.C02 and so on simply i wan access these columns
    through following Loop but unable to do so. It Understand the
    att_Rec.C01 as String .. Any Clue ???
    IF NOT attdays_cnt%ISOPEN
    THEN
    OPEN attdays_cnt;
    END IF;
    /* Keep fetching until no more records are FOUND */
    FETCH attdays_cnt INTO att_rec;
    message('Cursor Opened');
    WHILE attdays_cnt%FOUND
    LOOP
    a31_cnt:=1; -- reinitializtion of variables for other employees
    p_days:=0;
    w_days:=0;
    WHILE a31_cnt<32 LOOP
    IF concat('ATT_REC.C',to_char(a31_cnt,'00'))='L'='P' THEN
    p_days:=p_days+1;
    ELSE ATT_REC.C01='W' THEN
    w_days:=w_days+1;
    END IF;
    END LOOP;
    Message was edited by:
    Fiz Dosani

    Perhaps this is marginally simpler with nested table, YMMV ;-)
    (based on Elic's example)
    Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production
    SQL> CRE ATE TABLE t (i, j, k)
      2  AS
      3     SELECT LEVEL, POWER (LEVEL, 2), POWER (LEVEL, 3)
      4     FROM DUAL
      5     CONNECT BY LEVEL <= 5;
    Table created.
    SQL> CREATE OR REPLACE type ntt_number AS TABLE OF NUMBER;
      2  /
    Type created.
    SQL> SET SERVEROUTPUT ON;
    SQL> DECLARE
      2     TYPE t_tbl IS TABLE OF ntt_number;
      3
      4     var t_tbl;
      5  BEGIN
      6     SELECT ntt_number (i, j, k)
      7     BULK COLLECT INTO var
      8     FROM   t;
      9
    10     FOR i IN 1 .. var.COUNT LOOP
    11        FOR j IN 1 .. var (i).COUNT LOOP
    12           DBMS_OUTPUT.PUT_LINE (
    13              'var (' || i || ') (' || j || ') => ' || var (i) (j));
    14        END LOOP;
    15     END LOOP;
    16  END;
    17  /
    var (1) (1) => 1
    var (1) (2) => 1
    var (1) (3) => 1
    var (2) (1) => 2
    var (2) (2) => 4
    var (2) (3) => 8
    var (3) (1) => 3
    var (3) (2) => 9
    var (3) (3) => 27
    var (4) (1) => 4
    var (4) (2) => 16
    var (4) (3) => 64
    var (5) (1) => 5
    var (5) (2) => 25
    var (5) (3) => 125
    PL/SQL procedure successfully completed.
    SQL>

  • RE: (forte-users) Optimal number of records to fetch fromForte Cursor

    Guys,
    The behavior (1 fetch of 20000 vs 2 fetches of 10000 each) may also be DBMS
    related. There is potentially high overhead in opening a cursor and initially
    fetching the result table. I know this covers a great deal DBMS technology
    territory here but one explanation is that the same physical pages may have to
    be read twice when performing the query in 2 fetches as compared to doing it in
    one shot. Physical IO is perhaps the most expensive (vis a vis- resources)
    part of a query. Just a thought.
    "Rottier, Pascal" <[email protected]> on 11/15/99 01:34:22 PM
    To: "'Forte Users'" <[email protected]>
    cc: (bcc: Charlie Shell/Bsg/MetLife/US)
    Subject: RE: (forte-users) Optimal number of records to fetch from Forte C
    ursor
    The reason why a single fetch of 20.000 records performs less then
    2 fetches of 10.000 might be related to memory behaviour. Do you
    keep the first 10.000 records in memory when you fetch the next
    10.000? If not, then a single fetch of 20.000 records requires more
    memory then 2 fetches of 10.000. You might have some extra over-
    head of Forte requesting additional memory from the OS, garbage
    collections just before every request for memory and maybe even
    the OS swapping some memory pages to disk.
    This behaviour can be controlled by modifying the Minimum memory
    and Maximum memory of the partition, as well as the memory chunk
    size Forte uses to increment its memory.
    Upon partition startup, Forte requests the Minimum memory from the
    OS. Whithin this area, the actual memory being used grows, until
    it hits the ceiling of this space. This is when the garbage collector
    kicks in and removes all unreferenced objects. If this does not suffice
    to store the additional data, Forte requests 1 additional chunk of a
    predefined size. Now, the same behaviour is repeated in this, slightly
    larger piece of memory. Actual memory keeps growing until it hits
    the ceiling, upon which the garbage collector removes all unrefer-
    enced objects. If the garbage collector reduces the amount of
    memory being used to below the original Miminum memory, Forte
    will NOT return the additional chunk of memory to the OS. If the
    garbage collector fails to free enough memory to store the new data,
    Forte will request an additional chunk of memory. This process is
    repeated untill the Maximum memory is reached. If the garbage
    collector fails to free enough memory at this point, the process
    terminates gracelessly (which is what happens sooner or later when
    you have a memory leak; something most Forte developpers have
    seen once or twice).
    Pascal Rottier
    STP - MSS Support & Coordination Group
    Philip Morris Europe
    e-mail: [email protected]
    Phone: +49 (0)89-72472530
    +++++++++++++++++++++++++++++++++++
    Origin IT-services
    Desktop Business Solutions Rotterdam
    e-mail: [email protected]
    Phone: +31 (0)10-2428100
    +++++++++++++++++++++++++++++++++++
    /* All generalizations are false! */
    -----Original Message-----
    From: [email protected] [SMTP:[email protected]]
    Sent: Monday, November 15, 1999 6:53 PM
    To: [email protected]
    Subject: (forte-users) Optimal number of records to fetch from Forte
    Cursor
    Hello everybody:
    I 'd like to ask a very important question.
    I opened Forte cursor with approx 1.2 million records, and now I am trying
    to figure out the number of records per fetch to obtain
    the acceptable performance.
    To my surprise, fetching 100 records at once gave me approx 15 percent
    performance gain only in comparsion
    with fetching records each by each.
    I haven't found significant difference in performance fetching 100, 500
    or
    10.000 records at once.In the same time, fetching 20.000
    records at once make a performance approx 20% worse( this fact I cannot
    explain).
    Does anybody have any experience in how to improve performance fetching
    from
    Forte cursor with big number of rows ?
    Thank you in advance
    Genady Yoffe
    Software Engineer
    Descartes Systems Group Inc
    Waterloo On
    Canada
    For the archives, go to: http://lists.sageit.com/forte-users and use
    the login: forte and the password: archive. To unsubscribe, send in a new
    email the word: 'Unsubscribe' to: [email protected]
    For the archives, go to: http://lists.sageit.com/forte-users and use
    the login: forte and the password: archive. To unsubscribe, send in a new
    email the word: 'Unsubscribe' to: [email protected]

    Hi Kieran,
    According to your description, you are going to figure out what is the optimal number of records per partition, right? As per my understanding, this number was change by your hardware. The better hardware you have, the more number of records per partition.
    The earlier version of the performance guide for SQL Server 2005 Analysis Services Performance Guide stated this:
    "In general, the number of records per partition should not exceed 20 million. In addition, the size of a partition should not exceed 250 MB."
    Besides, the number of records is not the primary concern here. Rather, the main criterion is manageability and processing performance. Partitions can be processed in parallel, so the more there are the more can be processed at once. However, the more partitions
    you have the more things you have to manage. Here is some links which describe the partition optimization
    http://blogs.msdn.com/b/sqlcat/archive/2009/03/13/analysis-services-partition-size.aspx
    http://www.informit.com/articles/article.aspx?p=1554201&seqNum=2
    Regards,
    Charlie Liao
    TechNet Community Support

  • Fetch From Cursor

    In my Procedure I want to explicitly open the cursor and fetch from the cursor and again close the cursor
    I don’t want to use like this for some testingsomething:
    Create procedure kk
    Cur out sys_refcursor
    As
    Open cur for
    Select * from table;
    End
    I need to use like this
    Create procedure kk
    Cursor c is select * from table; need to return this cursor.
    As
    How to return that cursor
    Thanks

    maybe something like:
    create or replace procedure get_emp_name as
      cursor c1 is
        select * from emp;
      vEname emp.ename%type;
    begin
      open c1;
      fetch c1 into vEname;
      if c1%notfound then
         exit;
      end if;
      close c1;
    end;
    /or
    Create procedure get_emp_name as
      Cursor c1 is
       select *
         from emp;
    begin
      for c1_rec in c1 loop
         dbms_output.put_line('Emp Name: '||c1_rec.ename);
      end loop;
    end;
    /

  • Fetch from cursor when no records returned

    Hi,
    I've got the following question / problem?
    When I do a fetch from a cursor in my for loop and the cursor returns no record my variable 'r_item' keeps the value of the previous fetched record. Shouldn't it contain null if no record is found and I do a fetch after I closed and opend the cursor? Is there a way the clear the variable before each fetch?
    Below you find an example code
    CURSOR c_item (itm_id NUMBER) IS
    SELECT DISTINCT col1 from table1
    WHERE id = itm_id;
    r_item  c_item%ROWTYPE;
    FOR r_get_items IN c_get_items LOOP
      IF r_get_items.ENABLE = 'N' THEN       
          open c_item(r_get_items.ITMID);
          fetch c_item into r_item;
          close c_item;
          IF  r_item.ACCES = 'E' then
               action1
          ELSE                 
               action2
          END IF;
      END IF;
    END LOOP;  Thanx

    DECLARE
        CURSOR c_dept IS
          SELECT d.deptno
          ,      d.dname
          ,      d.loc
          ,      CURSOR (SELECT empno
                         ,      ename
                         ,      job
                         ,      hiredate
                         FROM   emp e
                         WHERE  e.deptno = d.deptno)
          FROM   dept d;
        TYPE refcursor IS REF CURSOR;
        emps refcursor;
        deptno dept.deptno%TYPE;
        dname dept.dname%TYPE;
        empno emp.empno%TYPE;
        ename emp.ename%TYPE;
        job emp.job%TYPE;
        hiredate emp.hiredate%TYPE;
        loc dept.loc%TYPE;
    BEGIN
       OPEN c_dept;
       LOOP
         FETCH c_dept INTO deptno, dname, loc, emps;
         EXIT WHEN c_dept%NOTFOUND;
         DBMS_OUTPUT.put_line ('Department : ' || dname);
         LOOP
           FETCH emps INTO empno, ename, job, hiredate;
           EXIT WHEN emps%NOTFOUND;
           DBMS_OUTPUT.put_line ('-- Employee : ' || ename);
         END LOOP;
      END LOOP;
      CLOSE c_dept;
    END;
    /like this...

  • Fetch from cursor variable

    Hello,
    I have a procedure, which specification is something like that:
    procedure proc1 (pcursor OUT SYS_REFCURSOR, parg1 IN NUMBER, parg2 IN NUMBER, ...);Inside the body of proc1 I have
    OPEN pcursor FOR
      SELECT column1,
                  column2,
                  CURSOR (SELECT column1, column2
                                    FROM table2
                                  WHERE <some clauses come here>) icursor1
          FROM table1
       WHERE <some clauses come here>;In a PL/SQL block I would like to execute proc1 and then to fetch from pcursor. This is what I am doing so far:
    DECLARE
      ldata SYS_REFCURSOR;
      larg1 NUMBER := 123;
      larg2 NUMBER := 456;
      outcolumn1 dbms_sql.Number_Table;
      outcolumn2 dbms_sql.Number_Table;
    BEGIN
      some_package_name.proc1 (ldata, larg1, larg2, ...);
      FETCH ldata BULK COLLECT INTO
        outcolumn1, outcolumn2,...,  *and here is my problem*;
    END;
    /How can I rewrite this in order to get the content of icursor1 ?
    Thanks a lot!

    Verdi wrote:
    How can I rewrite this in order to get the content of icursor1 ?
    Firstly ref cursors contain no data they are not result sets but pointers to compiled SQL statements.
    Re: OPEN cursor for large query
    PL/SQL 101 : Understanding Ref Cursors
    Ref cursors are not supposed to be used within PL/SQL or SQL for that matter, though people keep on insisting on doing this for some reason.
    http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10472/static.htm#CIHCJBJJ
    Purpose of Cursor Variables
    You use cursor variables to pass query result sets between PL/SQL stored subprograms and their clients. This is possible because PL/SQL and its clients share a pointer to the work area where the result set is stored.A ref cursor is supposed to be passed back to a procedural client language, such as Java or .Net.
    If you want to re-use a SQL statement in multiple other PL/SQL or SQL statements you would use a view.

  • Different error messages from different env while fetching ref cursor

    Hi<br>
    I have a package where i need to call one of the procedure.I this <br>
    procedure i am returning a refcursor as out parameter.Before returning refcursor i <br>
    am doing i am checking a condition if it is satisfied then I am saying return or else<br>
    it will proceed and refcursor is assigned for out parameter.So i am speakig about <br>
    the condition where i am exiting from procedure before refcursor parameter is <br>
    assigned .And later i am tring to fetch from that cursor .So i am getting different <br>
    kinds of errors which i described as follows <br>
    <br>
    <br>
    So If execute that procedure from sqlplus uing <br>
    <br>
    <br>
    var m ref cursor<br>
    DECLARE<br>
    Y NUMBER;<br>
    Z NUMBER;<br>
    A NUMBER;<br>
    BEGIN<br>
    A:=campa.dtl_inq(2,100070875,'R',Y,Z,:M);<br>
    END;<br>
    <br>
    Then if say<br>
    Print m<br>
    It gives <br>
    <br>
    ORA-24338: statement handle not executed<br>
    <br>
    And if i execute this using vb application <br>
    <br>
    I am getting following error <br>
    <br>
    ORA-01023: Cursor context not found (Invalid cursor number)<br>
    <br>
    So i am serching the reason for different errors<br>
    <br>
    Regards<br>
    vamsi krishna<br>

    The error depends on exactly what OCI calls the client software makes in accessing this invalid (null) ref cursor variable.
    It would seem that SQL*Plus makes different calls than what your code and Visual Basic does - thus the different error messages returned by the two applications.

  • SAVE EXCEPTIONS when fetching from cursors by BULK COLLECT possible?

    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bit Production
    Hello,
    I'm using an Cursor's FETCH by BULK COLLECT INTO mydata...
    Is it possible to SAVE EXCEPTIONS like with FORALL? Or is there any other possibility to handle exceptions during bulk-fetches?
    Regards,
    Martin

    The cursor's SELECT-statement uses TO_DATE(juldat,'J')-function (for converting an julian date value to DATE), but some rows contain an invalid juldat-value (leading to ORA-01854).
    I want to handle this "rows' exceptions" like in FORALL.
    But it could also be any other (non-Oracle/self-made) function within "any" BULK instruction raising (un)wanted exceptions... how can I handle these ones?
    Martin

  • Fetch Ref Cursor Multiple Times

    create or replace
    PROCEDURE refcursor1
    AS
    TYPE r_cursor IS REF CURSOR;
    rcv_emp r_cursor;
    TYPE rec_emp IS record
    empno NUMBER,
    ename VARCHAR2(20 CHAR),
    deptno number
    recv_emp rec_emp;
    recv_emp2 rec_emp;
    PROCEDURE printemployeedetails AS
    BEGIN
      loop
      fetch rcv_emp INTO recv_emp;
      exit WHEN rcv_emp%notfound;
        dbms_output.put_line(recv_emp.empno||'-'||recv_emp.ename||'-'||recv_emp.deptno);
      END loop;
    END;
    PROCEDURE printemployeedetails2(p_emp r_cursor) IS
    BEGIN
      loop
      fetch p_emp INTO recv_emp2;
      exit WHEN p_emp%notfound;
        dbms_output.put_line(recv_emp2.empno||'-'||recv_emp2.ename||'-'||recv_emp2.deptno);
      end loop;
    END;
    BEGIN
      FOR i IN (SELECT deptno FROM dept order by deptno)
      loop
        OPEN rcv_emp FOR SELECT empno,ename,deptno FROM emp WHERE deptno=i.deptno;
        dbms_output.put_line(i.deptno);
        dbms_output.put_line('--------------------');
        dbms_output.put_line('calling printemployeedetails');
        printemployeedetails;
        dbms_output.put_line('                    ');
        dbms_output.put_line('calling printemployeedetails2');
        dbms_output.put_line('                    ');
        printemployeedetails2(rcv_emp);
        CLOSE rcv_emp;
      END loop;
    end;
    Output:
    10
    calling printemployeedetails
    7839-KING-10
    7782-CLARK-10
    7934-MILLER-10
    calling printemployeedetails2
    20
    calling printemployeedetails
    7566-JONES-20
    7788-SCOTT-20
    7902-FORD-20
    7369-SMITH-20
    7876-ADAMS-20
    calling printemployeedetails2
    30
    calling printemployeedetails
    7698-BLAKE-30
    7499-ALLEN-30
    7521-WARD-30
    7654-MARTIN-30
    7844-TURNER-30
    7900-JAMES-30
    calling printemployeedetails2
    40
    calling printemployeedetails
    calling printemployeedetails2
    Hello All,
    If i open a cursor once can i fetch the elements of a cursor n times like above? i see only either one of those procedures are printing the details but not both.
    Wonder why as i am passing the same ref cursor to a second procedure.
    It's neither throwing me an error saying the elements of ref cursor are already fetched.
    Thank you.

    >
    If i open a cursor once can i fetch the elements of a cursor n times like above? i see only either one of those procedures are printing the details but not both.
    Wonder why as i am passing the same ref cursor to a second procedure.
    It's neither throwing me an error saying the elements of ref cursor are already fetched.
    >
    You can't see any such thing. That code above won't even compile let alone run.
    The 'ref cursor' you are talking about is defined in a standalone procedure 'refcursor1' which does NOTHING but declare some variables that are then NEVER USED.
    The other procedures try to use variables that DO NOT EXIST since they are not declared in the procedure that is trying to use them. So those procedures won't compile and even if they did compile and run each execution only does ONE fetch so the anonymous block can't possibly produce multiple rows of output.  
    I don't know what you claim to be seeing but it certainly isn't anything produced by the code you posted.

  • NLS Error on Second Fetch from Cursor

    Oracle 8i using PRO*C
    We have a UNIX (HP) environment (operational account) in which the NLS_LANG was not set for the shell. One of our applications opened a cursor for update and performed its first fetch. After processing it went back to fetch an additional buffer. At this point, the application failed with the following error: "SQLCODE: ORA-01890: NLS error detected". When we set the NLS_LANG enviroment variable this error disappeared.
    I need to know what the NLS_LANG enviroment variable is doing and why it is causing the second fetch to fail when it is not set so I can argue with the powers that be to have this paremeter always set for this accounts shell (i.e. globally). No-one really knows what this does here or why it would cause the cursor to fail, and so they are telling us to just set the variable in our own applications shell.
    I know the real answer to this is to set it up for the operational (global) shell but...
    Thanks in advance,
    Bill Rosmus

    it is difficult. The main problem is that you can't be sure that the function is called only once for each row.
    Why don't you simply run the cursor and the function separatly in pl/sql.
      CURSOR myCur IS SELECT myTable1.* FROM myTable1 ;
      SUBTYPE myRecType IS myCur%ROWTYPE ;
      funcResult varchar2(100); /* use the correct return datatype from your function here */
      FOR myRec in myCur LOOP
          BEGIN
             funcResult := myPackage.myFunc(myRec.column1);
          EXCEPTION
             WHEN myPackage.myFunc_Exception THEN
               <... do anything when fetched but function myFunc raised this exception ...>
          END ;
          <...do anything with row currently fetched>
       END LOOP;You even have more control where to handle the exception. Also there is one pl/sql context switch less. Since the function itself is pl/sql it could even be faster to run it in pl/sql then to call it from sql (inside a select).

Maybe you are looking for