PL/SQL Cursor function

I want to return all rows where the act_No is less than 3 (act_No's). However
I am using row count, but this will allow the first two rows to be printed out and nothing else. The problem is act_No should be accepted whether the values are 1 and 2 or 7 and 9 etc. The act_No refers to something that can only happen twice on a given date. Is there an alternative to rowcount? Here is the code;
CREATE OR REPLACE PROCEDURE add_vacc (pat_id in char, vis_vdate in date,
vis_act in number, vac_vacc in char)
AS
     /* declare variable to hold one row of patient */
     patrow patient%rowtype;
     act_No boolean;
     too_many_visits exception;
     vdate_too_early exception;
     PRAGMA EXCEPTION_INIT(too_many_visits,-20000);
     PRAGMA EXCEPTION_INIT(vdate_too_early,-20001);
     CURSOR p IS SELECT * INTO patrow
     FROM patient WHERE pid = pat_id;
BEGIN
     /* fetch patient row into patrow variable for pat_id entered as parameter */
     act_No := FALSE;
     FOR p_rec IN p LOOP
     IF p%rowcount > 2
          THEN DBMS_OUTPUT.PUT_LINE ('Error: Too many vaccinations for:' || p_rec.pname);
          DBMS_OUTPUT.PUT_LINE ('Cause: A patient can only have a maximum of 2 vaccinations per day');
          act_No := TRUE;
     END IF;
     DBMS_OUTPUT.PUT_LINE ('Patient Name: ' || p_rec.pname);
     DBMS_OUTPUT.PUT_LINE ('Patient Address: ' || trim(p_rec.address));
     /* trimmed address */
     DBMS_OUTPUT.PUT_LINE ('Insert attempted');
     INSERT into vaccinations (pid,vdate,action,vaccinated)
VALUES (pat_id,vis_vdate,vis_act,vac_vacc);
     END LOOP;
IF act_No = FALSE
THEN
     DBMS_OUTPUT.PUT_LINE ('action > 2');
     RAISE too_many_visits;
END IF;

while I'm not sure what you want, I think you should create a function that verifies your act_no because looks like no cursor function will help you here.

Similar Messages

  • Using cursor function in sql statement

    hi all
    can anyone plss explain why and when we will use cursor function in a sql statement like this and what is the difference while executing this sql statement with cursor function in comparison of a simple sql statement----
    select
    department_name,
    cursor (
    select last_name
    from employees e
    where e.department_id = d.department_id
    order by last_name
    ) the_employees
    from departments d
    thnx in advance

    RTFM
    http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/sqloperations.htm#sthref1452
    Cheers
    Sarma.

  • Building report from PL/SQL cursor

    Hello,
    is there any way to build APEX report using just PL/SQL cursor?
    I don't have grant to SELECT from views or tables, but I can use some functions returning row types and cursors. I know I can use them to build table from scratch with htp.p etc., but it’s not very nice. I want to do it using APEX reporting with filtering and pagination functionality.
    Is it possible?
    Regards,
    Przemek

    Apologies for the delay, I was out of the office.
    Below is a package serving as the basis for creating a view based on a pipelined function. The package is just a skeleton and will not compile in its current form, you will need to go through it filling in the blanks as described by the comments.
    If you want some control over what rows are returned by the view from a larger result set, use the set_parameters function in the WHERE clause, E.G.:
    select * from really_big_complicated_slow_view where 1 = view_pkg.set_parameters(something_that_reduces_the_view_result_set_size);
    Or, a more concrete example:
    select result_text from view_to_convert_to_csv where 1 = view_pkg.set_parameters(pi_table => 'my_table', pi_where = 'whatever');
    In the spirit of full disclosure, I got the idea for using the "set_parameters" function in the view WHERE clause from a post or blog somewhere a couple of years ago but have lost track of who actually deserves the credit for the good idea.
    -Tom
    create or replace package demo_vw as
    -- Package to serve as the basis for a view based on a function
    -- Customize this record so that it represents a row from this view...
    type row_type is record (
    -- record fields here
    type table_type is table of row_type;
    -- This function is used in the DDL to define the view, for example:
    -- create or replace view my_view (col1, col2, ..., colN) as
    -- select * from table(my_view_vw.get_view);
    function get_view
    return table_type
    pipelined;
    -- Customize this function header to accept the parameters for this view, if
    -- any. If this view does not require any parameters, the set_parameters
    -- function may be deleted.
    -- This function should always return 1 and is called as follows
    -- select <whatever>
    -- from my_view
    -- where 1 = my_view_vw.set_parameters(p1, p2, p3, ..., pN);
    function set_parameters (pi_whatever1 in whatever,
    pi_whateverN in whatever)
    return number;
    end demo_vw;
    show error package demo_vw
    create or replace package body demo_vw as
    -- Customize this list of private global variables to match the parameters
    -- required by the view. These variables are set, reset, and validated by
    -- set_parameters, reset_parameters, and valid_parameters respectively...
    g_var1 whatever;
    g_varN whatever;
    function set_parameters (pi_whatever1 in whatever,
    pi_whateverN in whatever)
    return number
    is
    -- Customize this function header to accept the parameters for this view, if
    -- any. If this view does not require any parameters, the set_parameters
    -- function may be deleted.
    -- This function should always return 1 and is called as follows
    -- select col1, col2, ..., colN
    -- from my_view
    -- where 1 = my_view_vw.set_parameters(p1, p2, p3, ..., pN);
    begin
    g_var1 := pi_whatever1;
    g_varN := pi_whateverN;
    return 1;
    end set_parameters;
    function valid_parameters
    return boolean
    is
    -- Customize...
    -- Assumes that set_parameters has been called to set the value of the view
    -- parameters.
    l_valid boolean := true;
    begin
    return l_valid;
    end valid_parameters;
    procedure reset_parameters
    is
    -- Customize...
    -- This is called at the end of the get_view function to reset the view
    -- parameters for the next caller.
    begin
    g_var1 := null;
    g_varN := null;
    end reset_parameters;
    function get_view
    return table_type
    pipelined
    is
    -- build and return each row for the view...
    l_row row_type;
    begin
    if valid_parameters then
    -- do your process to populate the l_row variable here...
    pipe row (l_row);
    end if;
    reset_parameters;
    exception
    when others then
    reset_parameters;
    raise;
    end get_view;
    end demo_vw;
    show error package body demo_vw
    create or replace view demo
    as
    select * from table(demo_vw.get_view);

  • Implicit PL/SQL cursors remain open, causing ORA-01000 (Client 9.2.0.1)

    Hello,
    since migrating our system from Oracle Client 9.0.X to 9.2.0.1 (Windows XP), i am encountering troubles when calling a stored procedure from a Cobol-Program:
    after a while i run into a 'Maximum open cursors exceeded'-message (ORA-01000)
    The stored procedure returns a cursor (ref_cursor)
    When Executing the stored procedure, there are actually 2 cursors involved, in fact the stored PL/SQL procedure implicitely opens a child-cursor when doing a select within the PL/SQL.
    After fetching the result and closing the cursor in my cobol-program, it correctly closes the cursor associated with the stored-procedure, but it does not close the cursor that was implicitely opened by oracle.
    After a while i am running into a Maximum open cursors message, because those cursors have not properly been closed.
    Here's a simple PL/SQL package that illustrates the problem:
    create or replace package scott.SCOTTS_PACKAGE is
    type ref_cursor IS REF CURSOR;
    function GET_EMP(EMP_IN CHAR) return ref_cursor;
    end SCOTTS_PACKAGE;
    create or replace package body scott.SCOTTS_PACKAGE is
    -- Function and procedure implementations
    function GET_EMP(EMP_IN CHAR) return ref_cursor is
    MyCurs ref_cursor;
    begin
    OPEN MyCurs FOR
    SELECT EMPNO ,
    ENAME ,
    JOB
    FROM SCOTT.EMP
    WHERE ENAME = EMP_IN;
    return(MyCurs);
    end;
    end SCOTTS_PACKAGE;
    Here are some exerpts from my cobol program:
    (The program iterates 100x through the section that executes the PL/SQL. After each iteration an additional open cursor remains in the database)
    003800 EXEC SQL BEGIN DECLARE SECTION END-EXEC.
    003900*
    004000 01 SQL-USERNAME PIC X(16) VARYING.
    004100 01 SQL-PASSWD PIC X(16) VARYING.
    004200 01 SQL-DBNAME PIC X(64) VARYING.
    004300 01 ORACLE.
    004700 02 ORA-CUR-EMP SQL-CURSOR.
    01 EMPREC.
    02 EMPREC-EMPNO PIC X(4).
    02 EMPREC-ENAME PIC X(10).
    02 EMPREC-JOB PIC X(9).
    005400 EXEC SQL END DECLARE SECTION END-EXEC.
    018400 PROCEDURE DIVISION.
    CONTINUE.
    018700 EXEC SQL
    018800 WHENEVER SQLERROR DO PERFORM SQL-ERROR
    018900 END-EXEC.
    019000*
    CONTINUE.
    019100 EXEC SQL
    019200 WHENEVER NOT FOUND DO PERFORM SQL-NOT-FOUND
    019300 END-EXEC.
    022400 EXEC SQL
    022500 ALLOCATE :ORA-CUR-EMP
    022600 END-EXEC
    PERFORM VARYING I FROM 1 BY 1 UNTIL I > 100
    ACCEPT DUMMY FROM TER
    IF DUMMY = "E"
    MOVE 100 TO I
    END-IF
    PERFORM GET-EMP
    ADD 1 TO I
    END-PERFORM
    119300 GET-EMP SECTION.
    119400************************
    119500 GAM0.
    MOVE SPACES TO EMPREC-EMPNO EMPREC-JOB
    MOVE "SMITH" TO EMPREC-ENAME
    120200 EXEC SQL AT SSSI EXECUTE
    120300 BEGIN
    120400 :ORA-CUR-EMP:=
    120500 SCOTT.SCOTTS_PACKAGE.GET_EMP(:EMPREC-ENAME );
    120900
    END;
    121000 END-EXEC
    121200 IF DB-ERR-CODE NOT = HIGH-VALUE
    121300 DISPLAY "CCSIFSO:GET-AUTRE-MATR:APPEL PERS... OK"
    121400 EXEC SQL
    121500 FETCH :ORA-CUR-EMP
    121600 INTO
    121700 :EMPREC-EMPNO,
    121800 :EMPREC-ENAME,
    121900 :EMPREC-JOB
    122400 END-EXEC
    122500 END-IF
    122600*
    122700 IF DB-ERR-CODE NOT = HIGH-VALUE
    122800 DISPLAY "CCSIFSO:GET-AUTRE-MATR:APPEL FETCH.. OK"
    123000 ELSE
    123100 MOVE LOW-VALUE TO DB-ERR-CODE
    123200 END-IF
    123300 EXEC SQL
    123400 CLOSE :ORA-CUR-EMP
    123500 END-EXEC
    123600 GA-EX.
    123700 EXIT.
    124000 SQL-NOT-FOUND SECTION.
    124100*----------------------
    124200 NF0.
    124300 DISPLAY "CCSIFSO:SQL-NOT-FOUND SECTION."
    124400 MOVE HIGH-VALUE TO DB-ERR-CODE.
    124500 NF-EX.
    124600 EXIT.
    124700*
    124800 SQL-ERROR SECTION.
    124900*-----------------
    125000 ER0.
    125200 EXEC SQL
    125300 WHENEVER SQLERROR CONTINUE
    125400 END-EXEC
    125700 MOVE HIGH-VALUE TO DB-ERR-CODE
    125800*
    126100 DISPLAY "ORACLE ERROR DETECTED: " SQLCODE UPON TER
    126200 DISPLAY SQLERRMC UPON TER
    126300*
    126400 EXEC SQL AT SSSI
    126500 ROLLBACK WORK
    126600 RELEASE
    126700 END-EXEC
    126800 DISPLAY "----------------------------" UPON TER
    126900 DISPLAY " ! ROLLBACK ET DISCONNECT ! " UPON TER
    127000 DISPLAY "----------------------------" UPON TER
    127200 CALL "PPTERMJ".
    127400 ER-EX.
    127500 EXIT.
    Finally here's an exerpt from V$OPEN_CURSOR, after a few iterations:
    1 begin :b1 := SCOTT . SCOTTS_PACKAGE . GET_EMP (:b2 ) ; END ;
    2 SELECT EMPNO , ENAME , JOB FROM EMP WHERE ENAME = :B1
    3 SELECT EMPNO , ENAME , JOB FROM EMP WHERE ENAME = :B1
    4 SELECT EMPNO , ENAME , JOB FROM EMP WHERE ENAME = :B1
    5 SELECT EMPNO , ENAME , JOB FROM EMP WHERE ENAME = :B1
    6 SELECT EMPNO , ENAME , JOB FROM EMP WHERE ENAME = :B1
    7 SELECT EMPNO , ENAME , JOB FROM EMP WHERE ENAME = :B1
    8 SELECT EMPNO , ENAME , JOB FROM EMP WHERE ENAME = :B1
    9 SELECT EMPNO , ENAME , JOB FROM EMP WHERE ENAME = :B1
    10 SELECT EMPNO , ENAME , JOB FROM EMP WHERE ENAME = :B1
    11 SELECT EMPNO , ENAME , JOB FROM EMP WHERE ENAME = :B1
    As you see, there is only 1 cursor starting with 'begin ... '
    but there are 10 implicit cursors 'SELECT EMPNO, ... ' that have not been properly closed, nor reused by ORACLE.
    In our old configuration (ORACLE CLient 9.0.X), you would only see:
    1 begin :b1 := SCOTT . SCOTTS_PACKAGE . GET_EMP (:b2 ) ; END ;
    2 SELECT EMPNO , ENAME , JOB FROM EMP WHERE ENAME = :B1
    meaning all the other cursors have properly been closed.
    As a conclusion: the program correctly closes the implicit cursors when using a 9.0 Client, wheras the implicit cursors remain open on Client 9.2.0.1 (Windows XP)
    The underlying database can be either 8.i or 9, the problem remains the same.
    Finally here's a small Delphi code, using ODAC-components, that somewhat illustrates the same problem:
    procedure TForm1.ExecProcClick(Sender: TObject);
    var I: INTEGER ;
    begin
    FOR I := 1 TO 5 DO
    BEGIN
    SP1.StoredProcName:='SCOTT.SCOTTS_PACKAGE.GET_EMP';
    SP1.Prepare;
    SP1.ParamByName('EMP_IN').AsString := 'SMITH';
    SP1.ExecProc;
    SP1.Next;
    SP1.Close;
    SP1.UnPrepare;
    END;
    end;
    After each call to 'PREPARE', an additional implicit cursor remains open on the database. (using Oracle Client 9.2.0.1)
    On our old system (Oracle Client 9.0 or 8.X), the same program would not generate accumulating open cursors on the database
    Any suggestions would be welcome,
    Claude

    Cobol.. been many years since I last even saw some Cobol source code. Invokes all kinds of memories. :-)
    Since you found the patch, the advice is superfluous, but works. Close the cursor at the PL/SQL side, e.g.
    create or replace procedure CloseRefCursor( cRefCursor TYPELIB.TRefCursor ) is
    begin
      close cRefCursor;
    exception when OTHERS then
      -- if the cursor is already gone, not a problem
      NULL;
    end;In Delphi for example, one can subclass the class used for ref cursor calls and add a call to the above PL/SQL proc in the destructor. Or add create a standard Cobol close ref cursor section that does similar.

  • Need a column based off a PL/SQL cursor, how to do this?

    Oracle9i Enterprise Edition Release 9.2.0.8.0 - 64bit Production
    With the Real Application Testing option
    JServer Release 9.2.0.8.0 - Production
    Report Builder 10.1.2.2.0
    ORACLE Server Release 10.1.0.5.0
    Oracle Procedure Builder 10.1.2.2.0
    Oracle ORACLE PL/SQL V10.1.0.5.0 - Production
    Oracle CORE     10.1.0.5.0     Production
    Hi,
    I am trying to create a fairly basic report but in the initial data model query, I have one column that is built based off of a PL/SQL cursor. How do I add this into my report? I have tried to create a function under Program Units and reference the function in my select statement for the data model however it keeps saying it is an invalid identifier, and I assume its looking in our database and not the function I created inside the report.
    This is what it looks like:
    SELECT   a.id,
             b.name,
             F_GET_GENERIC_NAME(b.code) "Generic Name",
             c.strength...and the function i want it to use in my report:
    FUNCTION F_GET_GENERIC_NAME (in_code varchar2) RETURN VARCHAR2 IS
    BEGIN
    DECLARE
    generic_name table.column%TYPE;
    CURSOR cs_get_generic_name IS
    SELECT /*+ USE_HASH (AR) */ desc
    FROM  a_ref AR, ai_ic AC    
    WHERE AC.code = in_code
    AND   AC.code = AR.code
    ORDER BY sort_nbr;
    BEGIN
           generic_name := '';
              FOR v_get_generic_name IN cs_get_generic_name
              LOOP
                 generic_name := generic_name || RTRIM(v_get_generic_name.desc)
                                     || '/' || ' ';
              END LOOP;
              generic_name := SUBSTR(generic_name, 1,(NVL(LENGTH(generic_name), 0) - 2));
    RETURN generic_name;
    END;
    END;
        Any suggestions? Should I just create the function in the database?

    I am trying to do it through a formula column but am encountering the following problem.
    I've created a formula column in my data model where I want the column to be (inside the group).
    Inside the PL/SQL for the column I reference the function that I had previously created with the following:
    function CF_Generic_nameFormula return Char is
    begin
         F_GET_GENERIC_NAME(:code);
    end;However it won't let me compile, giving the error that "F_GET_GENERIC_NAME is not a procedure or is undefined." Is there something else that I am missing?
    EDIT: Nevermind, i missed something simple like putting a return in front of the function call.
    Edited by: a small rabbit on Nov 3, 2009 10:43 AM
    Edited by: a small rabbit on Nov 3, 2009 10:44 AM

  • PL/SQL Pipelined Function to Compare *ANY*  2 tables

    I am trying to create a pipelined function in 10g R1 that will take the name of two tables, compare the the tables using dynamic SQL and pipe out the resulting rows using the appropriate row type. The pipelined function will be used in a DML insert statement.
    For example:
    create table a (f1 number, f2, date, f3 varchar2);
    create table b (f1 number, f2, date, f3 varchar2);
    create table c (f1 number, f2, date, f3 varchar2);
    create or replace TYPE AnyCollTyp IS TABLE OF ANYTYPE;
    create or replace TYPE CRowType IS c%ROWTYPE;
    create or replace TYPE CRowTabType IS table of CRowType;
    CREATE OR REPLACE FUNCTION compareTables (p_source IN VARCHAR2, p_dest IN VARCHAR2)
    RETURN AnyCollTyp PIPELINED
    IS
    CURSOR columnCur (p_tableName IN user_tab_columns.table_name%TYPE)
    IS
    SELECT column_name, column_id
    FROM user_tab_columns
    WHERE table_name = p_tableName
         ORDER BY column_id;
    l_cur sys_refcursor;
    l_rec ANYTYPE;
    l_stmt VARCHAR2 (32767);
    BEGIN
    l_stmt := 'select ';
    FOR columnRec IN columnCur (p_dest)
    LOOP
    l_stmt := l_stmt || CASE
    WHEN columnRec.column_id > 1
    THEN ','
    ELSE ''
    END || columnRec.column_name;
    END LOOP;
    l_stmt := l_stmt || ' from ' || p_source;
    l_stmt := l_stmt || ' minus ';
    l_stmt := l_stmt || ' select ';
    FOR columnRec IN columnCur (p_dest)
    LOOP
    l_stmt := l_stmt || CASE
    WHEN columnRec.column_id > 1
    THEN ','
    ELSE ''
    END || columnRec.column_name;
    END LOOP;
    l_stmt := l_stmt || ' from ' || p_dest;
    OPEN l_cur FOR l_stmt;
    LOOP
    FETCH l_cur
    INTO l_rec;
    PIPE ROW (l_rec);
    EXIT WHEN l_cur%NOTFOUND;
    END LOOP;
    CLOSE l_cur;
    RETURN;
    END compareTables;
    The pipelined function gets created without error. However, the testCompare procedure gets an error:
    SQL> create or replace procedure testCompare is
    begin
    insert into c
    select *
    from (TABLE(CAST(compareTables('a','b') as cRowTabType)));
    dbms_output.put_line(SQL%ROWCOUNT || ' rows inserted into c.');
    end;
    Warning: Procedure created with compilation errors.
    SQL> show errors
    Errors for PROCEDURE TESTCOMPARE:
    LINE/COL ERROR
    3/4 PL/SQL: SQL Statement ignored
    5/47 PL/SQL: ORA-22800: invalid user-defined type
    Does anyone know what I am doing wrong? Is there a better way to compare any two tables and get the resulting rows?

    904640 wrote:
    Hi All,
    Is it possible to post messages to weblogic JMS queue from pl/sql procedure/function?
    From this Queue, message will be read by OSB interface.
    Any help will be highly appreciated.
    http://www.lmgtfy.com/?q=oracle+pl/sql+weblogic+jms+queue

  • SQL Cursors HELP  ASAP

    I need somebody to help me with sql cursors, in JSP.
    This is my peace of code what is wrong with it?
              Statement stmt = myConn.createStatement();
              stmt.executeQuery("BEGIN WORK");
              stmt.executeQuery("DECLARE item_cursor CURSOR FOR SELECT user_name FROM admin_info");
              stmt.executeQuery("FETCH 10 FROM item_cursor");
              ResultSet rs = stmt.getResultSet();
              while(rs.next()){
                   if(rs.getString(1) != null){
                        user_name = rs.getString(1).trim();
    %><P><%= user_name %></P><%
              stmt.executeQuery("CLOSE item_cursor");
              stmt.executeQuery("COMMIT WORK");
    and this is the error that a get: No results where returned by the query
    Please help anybody
    thanx guys

    If you are using ORACLE drivers and classes.
    This sample program shows Oracle JDBC REF CURSOR functionality, creating a PL/SQL package that includes a stored function that returns a REF CURSOR type. The sample retrieves the REF CURSOR into a result set object.
    * This sample shows how to call a PL/SQL function that opens
    * a cursor and get the cursor back as a Java ResultSet.
    import java.sql.*;
    import java.io.*;
    import oracle.jdbc.driver.*;
    class RefCursorExample
    public static void main (String args [])
    throws SQLException
    // Load the driver
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    // Connect to the database
    // You can put a database name after the @ sign in the connection URL.
    Connection conn =
    DriverManager.getConnection ("jdbc:oracle:oci8:@", "scott", "tiger");
    // Create the stored procedure
    init (conn);
    // Prepare a PL/SQL call
    CallableStatement call =
    conn.prepareCall ("{ ? = call java_refcursor.job_listing (?)}");
    // Find out all the SALES person
    call.registerOutParameter (1, OracleTypes.CURSOR);
    call.setString (2, "SALESMAN");
    call.execute ();
    ResultSet rset = (ResultSet)call.getObject (1);
    // Dump the cursor
    while (rset.next ())
    System.out.println (rset.getString ("ENAME"));
    // Close all the resources
    rset.close();
    call.close();
    conn.close();
    // Utility function to create the stored procedure
    static void init (Connection conn)
    throws SQLException
    Statement stmt = conn.createStatement ();
    stmt.execute ("create or replace package java_refcursor as " +
    " type myrctype is ref cursor return EMP%ROWTYPE; " +
    " function job_listing (j varchar2) return myrctype; " +
    "end java_refcursor;");
    stmt.execute ("create or replace package body java_refcursor as " +
    " function job_listing (j varchar2) return myrctype is " +
    " rc myrctype; " +
    " begin " +
    " open rc for select * from emp where job = j; " +
    " return rc; " +
    " end; " +
    "end java_refcursor;");
    stmt.close();

  • Understanding SQL cursor attributes

    I was trying to understand the use of SQL cursor attributes.So i chose sql%notfound attribute to be used with an exception in the below example.
    create or replace procedure checkExcp
    is
    v_empName varchar2(30);
    exp_no_row_found exception;
    errorMessage varchar2(500);
    begin
    select ename into v_empName from emp where empno = '8000';
    if sql%notfound then
         raise exp_no_row_found ;
    end if;
    exception
    when exp_no_row_found
    then
      errorMessage := 'Error occured while executing updateInventoryTotalsInDB function: ';
    end;When i debugged this proc i realized that the
    if sql%notfound then
         raise exp_no_row_found ;bit of the code(and the custom exception exp_no_row_found) is useless. Because when no rows are returned by the query
    select ename into v_empName from emp where empno = '8000';it straightaway goes to the exception block bypassing the 'if sql%notfound....' bit. So when is a SQL cursor attribute like sql%notfound useful?

    But i want to add specific error messages to each
    SELECT...INTO statements. So a single,common
    NO_DATA_FOUND exception would mask these specific
    errors.Then don't make it a single, common exception block. Have specific execution blocks with their own exception block for each different way you want to handle the exception e.g.
    BEGIN
      BEGIN
        SELECT mydata INTO myvar FROM mytable;
      EXCEPTION
        WHEN NO_DATA_FOUND THEN
          myvar := 'No data for myvar';
      END;
      BEGIN
        SELECT myotherdata INTO myvar2 FROM mytable;
      EXCEPTION
        WHEN NO_DATA_FOUND THEN
          myvar2 := 'No data for myvar2';
      END;
    END;Nested execution blocks are your friend when you want to handle exceptions for specific areas.

  • Help with "ORA-06511: PL/SQL: cursor already open"

    I've tried numerous variations on this piece of code and I always get the same result. I'm sure this is painfully obvious to an experienced PL/SQL person.
    Any help will be appreciated!
    Thank You!
    1 DECLARE
    2 CURSOR EMP_CURSOR IS SELECT last_name from employees;
    3 current_last_name varchar2(25);
    4 BEGIN
    5 IF EMP_CURSOR%ISOPEN
    6 THEN
    7 dbms_output.put_line ('cursor is already open');
    8 close EMP_CURSOR;
    9 END IF;
    10 dbms_output.put_line ('opening cursor');
    11 OPEN EMP_CURSOR;
    12 FOR item in EMP_CURSOR LOOP
    13 FETCH EMP_CURSOR INTO current_last_name;
    14 EXIT WHEN EMP_CURSOR%NOTFOUND;
    15 dbms_output.put_line (item.last_name);
    16 END LOOP;
    17 CLOSE EMP_CURSOR;
    18* END;
    19 /
    DECLARE
    ERROR at line 1:
    ORA-06511: PL/SQL: cursor already open
    ORA-06512: at line 2
    ORA-06512: at line 12

    Mathieu,
    Log in as anotherSchema and grant select on 'IDsTable' to the current user.
    SQL> r
      1  create or replace function f1(theID varchar2) return mytype pipelined is
      2  out varchar2(30);
      3  cursor myCursor (x varchar2) is select * from scott.emp where job=x;
      4  begin
      5  for rec in myCursor(theID) loop
      6  pipe row(rec.ename);
      7  end loop;
      8  return;
      9* end;
    Warning: Function created with compilation errors.
    SQL> show errors
    Errors for FUNCTION F1:
    LINE/COL ERROR
    3/33     PL/SQL: SQL Statement ignored
    3/53     PL/SQL: ORA-00942: table or view does not exist
    6/1      PL/SQL: Statement ignored
    6/10     PLS-00364: loop index variable 'REC' use is invalid
    SQL> connect scott
    Enter password: *****
    Connected.
    SQL> grant select on emp to testuser;
    Grant succeeded.
    SQL> connect testuser
    Enter password: ****
    Connected.
    SQL> create or replace function f1(theID varchar2) return mytype pipelined is
      2  out varchar2(30);
      3  cursor myCursor (x varchar2) is select * from scott.emp where job=x;
      4  begin
      5  for rec in myCursor(theID) loop
      6  pipe row(rec.ename);
      7  end loop;
      8  return;
      9  end;
    10  /
    Function created.
    SQL> disconnect
    Disconnected from Oracle9i Enterprise Edition Release 9.2.0.3.0 - 64bit Production
    With the Partitioning option
    JServer Release 9.2.0.3.0 - Production
    SQL>

  • Logical Operations in SQL decode function ?

    Hi,
    Is it possible to do Logical Operations in SQL decode function
    like
    '>'
    '<'
    '>='
    '<='
    '<>'
    not in
    in
    not null
    is null
    eg...
    select col1 ,order_by,decode ( col1 , > 10 , 0 , 1)
    from tab;
    select col1 ,order_by,decode ( col1 , <> 10 , 0 , 1)
    from tab;
    select col1 ,order_by,decode ( col1 , not in (10,11,12) , 0 , 1)
    from tab;
    select col1 ,order_by,decode ( col1 ,is null , 0 , 1)
    from tab;
    Regards,
    infan
    Edited by: user780731 on Apr 30, 2009 12:07 AM
    Edited by: user780731 on Apr 30, 2009 12:07 AM
    Edited by: user780731 on Apr 30, 2009 12:08 AM
    Edited by: user780731 on Apr 30, 2009 12:08 AM
    Edited by: user780731 on Apr 30, 2009 12:09 AM

    example:
    select col1 ,order_by,case when col1 > 10 then 0 else 1 end
    from tab;
    select col1 ,order_by,case when col1 &lt;&gt; 10 then 0 else 1 end
    from tab;
    select col1 ,order_by,case when col1 not in (10,11,12) then 0 else 1 end
    from tab;As for testing for null, decode handles that by default anyway so you can have decode or case easily..
    select col1 ,order_by,decode (col1, null , 0 , 1)
    from tab;
    select col1 ,order_by,case when col1 is null then 0 else 1 end
    from tab;

  • How to Passing clob to PL/SQL pipeline function

    I have a PL/SQL stored function which takes clob as input parameter and sends the results in a pipe line.
    create or replace function GetIds(p_list clob, p_del varchar2 := ',') return ideset_t pipelined is
    I am using ojdbc14.jar (Oracle 10g driver) with oracle 9i (9.2.0.1.0).
    I want to use the following SQL Query select * from table(GetIds(clob))
    Now the question is how can I pass the clob from JDBC?
    Here is my client code
    PreparedStatement stmt = con.prepareStatement("SELECT COLUMN_VALUE FROM TABLE(GETIDS(?, ','))");
    stmt.setCharacterStream(1, new StringReader(str), str.length());
    stmt.executeQuery();
    I get the following error when I try to run the program. The same thing works fine if the chracter lenght is less than some chaaracters.
    java.sql.SQLException: ORA-01460: unimplemented or unreasonable conversion requested
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:125)
         at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:305)
         at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:272)
         at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:623)
         at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:181)
         at oracle.jdbc.driver.T4CPreparedStatement.execute_for_describe(T4CPreparedStatement.java:420)
         at oracle.jdbc.driver.OracleStatement.execute_maybe_describe(OracleStatement.java:896)
         at oracle.jdbc.driver.T4CPreparedStatement.execute_maybe_describe(T4CPreparedStatement.java:452)
         at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:986)
         at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:2888)
         at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:2960)
         at Test.main(Test.java:42)
    Exception in thread "main"
    The setChracterStream works for any insert/update clob. Example when I tried the query (INSERT INTO CLOB_TEST VALUES(?)) setCharacterStream just works fine.
    Please any one can help me how to solve this.
    Thanks in advance.

    Hóla LuÃs,
    when you pick the PL/SQL function body returning a boolean, it implicitly means that TRUE means OK, while FALSE means error, always.
    In order to associate such error to a given form field, you have to go back to the page definiton / validations and specify the name of the item in the corresponding field.
    When you first create the validation rule, this value is not present even if you ask for the error message inline with the field.
    The error message text can be specified in the validation definition, if I am not wrong.
    When you need to return special error messages, including dynamic content for instance, you can use the Function Returning Error Message type, which reports an error when the string returned by the function is not null. This comes in handy when you want to display an item's code, for example, rather than generic text.
    Even in this case, you must go back to the validation and specify the name of the field if you want to see it inline.
    Hope it helps,
    Flavio

  • Error while executing Procedure - ORA-06511: PL/SQL: cursor already open

    I have successfully compiled the following procedure but when I execute it, following error occurs, please adv.
    Thanks and Regards,
    Luqman
    create or replace
    procedure TESTKIBOR
    (contno in varchar)
    AS
    BEGIN
    DECLARE cursor c1 is
    SELECT * FROM KIBOR_SCHEDULE
    WHERE CN=contno;
    begin
    OPEN C1;
    FOR line IN c1 LOOP
    update kibor_schedule
    set lincome=line.Lincome,
    expo=line.eXPO,
    pport=line.pPORT
    where cn=line.cn
    and rno=line.rno;
    END LOOP;
    COMMIT;
    close c1;
    END;
    END TESTKIBOR;
    ERROR at line 1:
    ORA-06511: PL/SQL: cursor already open
    ORA-06512: at "MKTG.TESTKIBOR", line 6
    ORA-06512: at "MKTG.TESTKIBOR", line 10
    ORA-06512: at line 1

    Hi,
    CREATE OR REPLACE PROCEDURE Testkibor
         (contno  IN VARCHAR)
    AS
    BEGIN
      DECLARE
        CURSOR c1 IS
          SELECT *
          FROM   kibor_schedule
          WHERE  cn = contno;
      BEGIN
    --//    OPEN c1; --no need to open if using for loop
        FOR line IN c1 LOOP
          UPDATE kibor_schedule
          SET    lincome = line.lincome,
                 expo = line.expo,
                 pport = line.pport
          WHERE  cn = line.cn
                 AND rno = line.rno;
        END LOOP;
        COMMIT;
    --//     CLOSE c1; -- no need for loop  does it for you
      END;
    END testkibor;SS

  • Need help on Dynamic SQL Cursor in Forms

    Hi All,
    I am trying to execute Dynamic SQL Cursor in forms using EXEC_SQL built in.
    I have a cursor for example:
    'select * from supplier where supplier = '||p_supplier||' and processing_order = '||p_order
    My code is
    cur_num := Exec_SQL.Open_cursor;
    sql_order := 'select * from supplier where supplier = '||p_supplier||' and processing_order = '||p_order;
    EXEC_SQL.PARSE(cursor_number, sql_order);
      EXEC_SQL.DEFINE_COLUMN(cur_num ,1,ln_Supp_Id);
      EXEC_SQL.DEFINE_COLUMN(cur_num ,2,ls_Suppl_Name,30);
    EXEC_SQL.DEFINE_COLUMN(cur_num ,24,ls_exchange,20);
      sql_count := EXEC_SQL.EXECUTE(cur_num );
      While EXEC_SQL.FETCH_ROWS(cur_num ) > 0 Loop
            EXEC_SQL.COLUMN_VALUE(cur_num ,1,ln_Supp_Id);
            EXEC_SQL.COLUMN_VALUE(cur_num ,2,ls_Suppl_Name);
            EXEC_SQL.COLUMN_VALUE(cur_num ,24,ls_exchange);
    End Loop;
    EXEC_SQL.CLOSE_CURSOR(cur_num );
    In this case I have to write 24 Define Columns and 24 Column value. Is there any way to assign them to %rowtype at one time as I need all coulmn of the table.
    I had similar case on multiple tables.
    Please help me
    Thanks,
    Maddy

    I need this dynamic sql because p_supplier and p_order values changes at run time
    I do not understand. Is this a simplified sample or the real thing? You do know that you can pass variables to cursors:
    cursor test is
    select * from supplier where supplier = p_supplier and processing_order = p_order;
    or does e.g. p_supplier hold other parts of the query?
    cheers

  • SQL query, function or SP for converting varbinary to image(.jpg format).

    Dear Sir/Mam
    I want SQL query, function or SP which converts binary data to image (.jpg format).
    I m able to convert image (.jpg format) to varbinary. But not able to convert vice versa.
    thanks in advance.

    Binary data is binary data - "image" is only an intrepretation of binary data.  Therefore your question makes little sense in the context of sql server since it does not have any facilities to utilize images.  Since you provide no context, I'm
    guessing that you are trying to retrieve an image stored in the database in a varbinary column and have your application use it as an image.  If so, you should post your question to a forum that is specific to your development environment.  

  • Query of queries disallows SQL right() function

    We're attempting to do a query of queries using the SQL
    right() function like this:
    select *
    from getresults
    where right([key],charindex('\',reverse([key]),1)-1) not in
    (#quotedvaluelist(getexcluded.file_name)#)
    We've even replaced that where clause with a much more simple
    where right([key])='m'
    just to make sure that it wasn't the nesting functions that
    were causing the problem.
    In either case, we get the error:
    Query of Queries syntax error.
    Encountered "right" at line 0, column 0. Incorrect
    conditional expression,
    Expected one of [like|null|between|in|comparison] condition,
    What SQL functions are disallowed from query of queries?
    Thanks,
    Kris

    Nasty stuff huh. Just happened to discover myself today that
    Left doesn't work. I'd suspect that Aggregate functions are the
    ONLY ones that will work. It would have been nice if they'd at
    least allowed CF vs DB functions in their own "database" language.
    BTW, also discovered that Count() returns Null rather than 0
    when there aren't any per your WHERE clause.

Maybe you are looking for