Ref cursor trouble

Hi All,
My requirement is to fetch values from any given tables through ref cursor, so i have used a below procedure
CREATE OR REPLACE
PROCEDURE et1(
    tab_name IN VARCHAR2,
    c1 OUT sys_refcursor)
AS
  v_prim_val VARCHAR2(2000);
  v_sql      VARCHAR2(2000);
BEGIN
  SELECT wm_concat(s.column_name)
  INTO v_prim_val
  FROM user_cons_columns s ,
    user_constraints c
  WHERE c.constraint_name=s.constraint_name
  AND c.constraint_type  ='P'
  AND s.table_name       =tab_name;
  dbms_output.put_line('Col val='||v_prim_val);
  v_sql:='select '||v_prim_val|| ' from easy where id in (1,2,3)';
  OPEN c1 FOR v_sql;
END et1;
/Problem with above code is the record set returned by ref cursor will be unknown so in which variable should i put it in?
below code will create table for above procedure
create table easy(id integer, event_rowid integer,txn_rowid integer,txn_name varchar2(200));
begin
for i in 1..5 loop
insert into easy values(i,'777'||i,i||89,'Ris'||i||i);
end loop;
end;
commit;
alter table easy add constraint pk_easy primary key(id,event_rowid,txn_name);While googling i found "we can't fetch into a variable of the weak cursor's row type." But I don't know the record set or the variables being returned .
Please help!

983088 wrote:
Is there alternative for wm_concat?Read the FAQ: {message:id=9360005}
under the string aggregation techniques
Thanks Billy for your reply
I had a requirement and i tried something , apparently it's a fiasco
I understand static sql is the key but not for my Lock.
I have 300 tables in my Database ,I have to fetch primary key and there values on some condition which user will pass .So, you're saying a user should be able to extract any data they want from any table of their choice with any conditions they want? Such 'users' are usually technical administrators who know the database and are trusted not to damage things.
Now please tell me when i don't know which table they will pass and table may have any number of primary keys and if i have used dynamic sql so what's wrong in that?It means that your business requirement is too 'generic' and there is no solid design to what the requirements are.
what approach should i follow?Use the DBMS_SQL package. This allows a 'dynamic' query to be constructed, parsed (and thus validated) and then queried where you can fetch the columns by numeric position (column number 1, column number 2 etc.) as well as determining their datatypes and names etc.
An example from my standard library of examples, where I use DBMS_SQL to take any query and extract the details of that query to output the data returned as a CSV file...
As sys user:
CREATE OR REPLACE DIRECTORY TEST_DIR AS '\tmp\myfiles'
GRANT READ, WRITE ON DIRECTORY TEST_DIR TO myuser
/As myuser:
CREATE OR REPLACE PROCEDURE run_query(p_sql IN VARCHAR2
                                     ,p_dir IN VARCHAR2
                                     ,p_header_file IN VARCHAR2
                                     ,p_data_file IN VARCHAR2 := NULL) IS
  v_finaltxt  VARCHAR2(4000);
  v_v_val     VARCHAR2(4000);
  v_n_val     NUMBER;
  v_d_val     DATE;
  v_ret       NUMBER;
  c           NUMBER;
  d           NUMBER;
  col_cnt     INTEGER;
  f           BOOLEAN;
  rec_tab     DBMS_SQL.DESC_TAB;
  col_num     NUMBER;
  v_fh        UTL_FILE.FILE_TYPE;
  v_samefile  BOOLEAN := (NVL(p_data_file,p_header_file) = p_header_file);
BEGIN
  c := DBMS_SQL.OPEN_CURSOR;
  DBMS_SQL.PARSE(c, p_sql, DBMS_SQL.NATIVE);
  d := DBMS_SQL.EXECUTE(c);
  DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
  FOR j in 1..col_cnt
  LOOP
    CASE rec_tab(j).col_type
      WHEN 1 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);
      WHEN 2 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_n_val);
      WHEN 12 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_d_val);
    ELSE
      DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);
    END CASE;
  END LOOP;
  -- This part outputs the HEADER
  v_fh := UTL_FILE.FOPEN(upper(p_dir),p_header_file,'w',32767);
  FOR j in 1..col_cnt
  LOOP
    v_finaltxt := ltrim(v_finaltxt||','||lower(rec_tab(j).col_name),',');
  END LOOP;
  --  DBMS_OUTPUT.PUT_LINE(v_finaltxt);
  UTL_FILE.PUT_LINE(v_fh, v_finaltxt);
  IF NOT v_samefile THEN
    UTL_FILE.FCLOSE(v_fh);
  END IF;
  -- This part outputs the DATA
  IF NOT v_samefile THEN
    v_fh := UTL_FILE.FOPEN(upper(p_dir),p_data_file,'w',32767);
  END IF;
  LOOP
    v_ret := DBMS_SQL.FETCH_ROWS(c);
    EXIT WHEN v_ret = 0;
    v_finaltxt := NULL;
    FOR j in 1..col_cnt
    LOOP
      CASE rec_tab(j).col_type
        WHEN 1 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
                    v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
        WHEN 2 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_n_val);
                    v_finaltxt := ltrim(v_finaltxt||','||v_n_val,',');
        WHEN 12 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_d_val);
                    v_finaltxt := ltrim(v_finaltxt||','||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'),',');
      ELSE
        DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
        v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
      END CASE;
    END LOOP;
  --  DBMS_OUTPUT.PUT_LINE(v_finaltxt);
    UTL_FILE.PUT_LINE(v_fh, v_finaltxt);
  END LOOP;
  UTL_FILE.FCLOSE(v_fh);
  DBMS_SQL.CLOSE_CURSOR(c);
END;This allows for the header row and the data to be written to seperate files if required.
e.g.
SQL> exec run_query('select * from emp','TEST_DIR','output.txt');
PL/SQL procedure successfully completed.Output.txt file contains:
empno,ename,job,mgr,hiredate,sal,comm,deptno
7369,"SMITH","CLERK",7902,17/12/1980 00:00:00,800,,20
7499,"ALLEN","SALESMAN",7698,20/02/1981 00:00:00,1600,300,30
7521,"WARD","SALESMAN",7698,22/02/1981 00:00:00,1250,500,30
7566,"JONES","MANAGER",7839,02/04/1981 00:00:00,2975,,20
7654,"MARTIN","SALESMAN",7698,28/09/1981 00:00:00,1250,1400,30
7698,"BLAKE","MANAGER",7839,01/05/1981 00:00:00,2850,,30
7782,"CLARK","MANAGER",7839,09/06/1981 00:00:00,2450,,10
7788,"SCOTT","ANALYST",7566,19/04/1987 00:00:00,3000,,20
7839,"KING","PRESIDENT",,17/11/1981 00:00:00,5000,,10
7844,"TURNER","SALESMAN",7698,08/09/1981 00:00:00,1500,0,30
7876,"ADAMS","CLERK",7788,23/05/1987 00:00:00,1100,,20
7900,"JAMES","CLERK",7698,03/12/1981 00:00:00,950,,30
7902,"FORD","ANALYST",7566,03/12/1981 00:00:00,3000,,20
7934,"MILLER","CLERK",7782,23/01/1982 00:00:00,1300,,10-----
Billy ,BTW u made my day i was just telling my girlfriend i got a reply from Oracle Ace, THXSmall things please ....

Similar Messages

  • Trouble with Bulk Collect to Ref cursor

    I'm trying to open a ref cursor to a dynamic query, and the fetch the cursor (BULK COLLECT)to the table type variable.But I keep getting the compilation error as 'PLS-00597: expression 'EMP_RESULTSET' in the INTO list is of wrong type'
    But when I use a simple select from a table and Bulk Collect directly to the table type variable it works. But that is not what I want.
    Can someone tell me where I have gone wrong in this stored proc I have listed below.
    your help will be highly appreciated.
    PROCEDURE SP_TEST_EMP_TABLE_TYPE (
          p_resultset OUT result_cursor          -- ref cursor as out parameter
       AS
        TYPE TYPE_REC_EMP is RECORD(EMPNO EMPLOYEE.EMPNO%TYPE, JOIN_DATE EMPLOYEE.JOIN_DATE%TYPE, SALARY EMPLOYEE.SALARY%TYPE); -- declare record type
        TYPE TYPE_TAB_EMP IS TABLE OF TYPE_REC_EMP;    -- declare table type
        EMP_RESULTSET TYPE_TAB_EMP; -- declare variable of type type_calendar_avail_resultset  
        SQUERY VARCHAR2(32000):='';
       BEGIN
        SQUERY:='SELECT EMPNO,JOIN_DATE,SALARY FROM EMPLOYEE WHERE EMPNO= 1001 AND JOIN_DATE=''20070530'' ';
        --select EMPNO,JOIN_DATE,SALARY BULK COLLECT INTO EMP_RESULTSET from  EMPLOYEE WHERE EMPNO=1001 AND JOIN_DATE='20070525';
        OPEN p_resultset FOR SQUERY;
          FETCH p_resultset BULK COLLECT INTO EMP_RESULTSET;
      EXCEPTION
          WHEN NO_DATA_FOUND
          THEN
             NULL;
          WHEN OTHERS
          THEN
             DBMS_OUTPUT.put_line (SQLERRM (SQLCODE));   
       END SP_TEST_EMP_TABLE_TYPE ;

    > i) I use a ref cursor to return back to the java
    front end, so I had to use a ref cursor.
    What is a ref cursor? It is not a data set. It is a pointer to a "SQL program". This program is created by the SQL Engine and the CBO that parses the SQL source code and determine an execution plan to get to the requested rows.
    When the client fetches from a (ref) cursor, the client is running this program and it find and returns the next row.
    There is no such thing as a physical result set for a cursor - no "copy" of the rows found for the source code SQL is made as a result set.
    > ii) I also use a dynamic sql, but I was thinking it
    wasn't useful for this posting, so tried to write a
    simple sql
    What is dynamic SQL? SQL where object names (e.g name of the table) is only known at run-time. Or where the filter (e.g. WHERE conditions) can only be determined at run time.
    If these are known, the SQL is static SQL.
    For both static and dynamic SQL, bind variables are critical. It is the biggest performance mistake (in Oracle) to hardcode values and literals into a SQL.
    > ii) I use a Bulk Collect to the table type
    collection, since I use a loop, for which I had to
    collect the results from each loop and finally send
    the resultset thru the ref cursor.
    Impossible. Nor does it make any sense. As stated, a ref cursor is a program and not a result set.
    What you intend to do is run a SQL against data. Copy this data into private/local PL/SQL memory. Construct another SQL against this data - which means that it needs to be shipped back to the SQL engine as it cannot use/read local PL/SQL memory structures. And the pass that SQL cursor to the client.
    What for?
    > I had earlier used the logic to for this using a
    temporary table, which works perfectly fine, but our
    DBA says we should avoid temporary tables since it
    makes additional read/write to the disk. This is the
    reason I'm using table type collection here.
    Your DBA is correct. One should so a single pass through a data set. Which is why simply passing a ref cursor for a SQL statement to the client is the simplest.
    It makes no sense copying SQL data into a collection and then copying that back into the SQL engine in order to throw a ref cursor around it.
    Basic client-server fundamentals.
    And why RTFM the Oracle manuals I've indicated is important. You need to understand the memory and processing architectures in Oracle in order to make an informed and correct decision.

  • How to open a Ref cursor in Oracle Reports

    I have a stored procedure that returns a ref cursor as an output parameter. I want to call this stored procedure in Oracle Reports After Form trigger. I am having trouble with the syntax of the output parameter. Event_record is the name of the cursor.
    After Form Trigger
    pkg_DEAL_WHITESHEET_CONCERTS.prc_Event_Information(:p_field_6,event_record);
    Error: Event_record must be declared

    Re-Write the procedure as Package Spec and Body. Declare the REFCursor in the Package Spec. Probably that helps.

  • Using BIND VARIABLES in REF CURSOR(s)

    Hello I am having trouble making my pl/sql program work using bind variables.
    here is a little snipit from my code:
    declare
    type ref_type is REF CURSOR;
    ref_cursor ref_type;
    summation_table varchar2(4000);
    begin
    summation_table := 'table_sum tsum';
    open ref_cursor for
    select * from :summation_table
    where tsum.revenue = 1000
    USING summation_table;
    end;
    The Error that I get is
    "bad bind variable 'summation_table'"
    could someone please help? I think the way 'tsum' is used could be a problem, but I don't know.

    SQL> CREATE TABLE TABLE_SUM(REVENUE NUMBER(10),
      2                         OTHER   NUMBER(10));
    Table created.
    SQL> INSERT INTO TABLE_SUM VALUES(1000,1);
    1 row created.
    SQL> INSERT INTO TABLE_SUM VALUES(1000,2);
    1 row created.
    SQL> variable alpha refcursor
    SQL> INSERT INTO TABLE_SUM VALUES(2000,3);
    1 row created.
    SQL> DECLARE
      2     summation_table varchar2(30) := 'table_sum tsum';
      3     PROCEDURE MYTEST(p_out out sys_refcursor)
      4     IS
      5     BEGIN
      6       OPEN p_out for 'select * from '||summation_table||
      7                      ' where tsum.revenue = :val' using 1000;
      8     END;
      9  BEGIN
    10     MYTEST(:alpha);
    11  END;
    12  /
    PL/SQL procedure successfully completed.
    SQL> print alpha
       REVENUE      OTHER
          1000          1
          1000          2
    SQL>

  • Getting a ref cursor out of a procedure

    Hello,
    I am having some issues getting the ref cursor out of this procedure that returns a ref cursor when given inputs.
    I have included the code below and made bold the call to the package and procedure where the requested function lies. I put c2 in the first parameter because that is the out and is defined first in the procedure. Am I going about this the wrong way? I am mainly a .NET developer and am still learning the syntax of PL/SQL.
    Thanks!
    Jeffrey Kevin Pry
    DECLARE
    TYPE r_cursor IS REF CURSOR;
    c2 r_cursor;
    CURSOR c1
    IS
    SELECT *
    FROM ELEMENT E
    WHERE E.SUBTYPE_CD = 'PAT';
    BEGIN
    FOR ROW_ITEM IN c1
    LOOP
    PKG_DTEST.GET_CHILDREN(c2,ROW_ITEM.ELEMENT_ID,1);
    FOR ROW_ITEM2 in c2
    LOOP
    dbms_output.put_line(ROW_ITEM2.ELEMENT_ID);
    END LOOP;
    END LOOP;
    END;
    Edited by: jeffrey.pry on Jan 21, 2011 6:01 AM

    You should probably post the code of PKG_DTEST.GET_CHILDREN as well as the error you are getting. It's hard to troubleshoot without knowing all the parts and pieces.
    Additionally, I see that you are using a nested FOR loop to process your data. You should rethink this. The best way to process data in Oracle is to compact it all into a single SQL statement if possible. If you are having trouble doing this please post the following and we can help.
    1. Oracle version (SELECT * FROM V$VERSION)
    2. Sample data in the form of CREATE / INSERT statements.
    3. Expected output
    4. Explanation of expected output (A.K.A. "business logic")
    5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Can a dynamic select stmt in a ref cursor be done?

    Hello all!
    I have a form in which a user can select a number of checkboxes that coorespond to fields in a table. After checking the desired boxes, the user can then click on a button and a variable (v_query) in a "when button pressed" trigger is populated with the text of a sql query. The trouble is, I want to incorporate the code contained in v_query into the REF cursor OPEN statement where it is expecting a sql query. The idea here is that the cursor would loop through the table fetching rows based on the select statement variable (v_query) and write them to a file using TEXT_IO(See below code). First, can this be done? Second, is there a better way to do accomplish this?
    DECLARE
    TYPE t_cur IS REF CURSOR ; -- define t_cur as a type
    c_cur t_cur ; -- define an actual variable of type t_cur
    r_emp emp%ROWTYPE ; -- PL/SQL record to hold row
    v_query VARCHAR2(2000) := 'SELECT * FROM emp' ; -- the query!
    BEGIN
    -- OPEN FILE
    out_file := Text_IO.Fopen('C:\BACHELOR\TEST.txt', 'w');
    OPEN c_cur FOR v_query ; -- v_query could contain any valid query
    LOOP
    FETCH c_cur INTO r_emp ; -- get first row from dataset
    EXIT WHEN %NOTFOUND
    --PRINT TO FILE 
              Text_IO.Put_line(out_file, r_emp);
              Text_IO.New_Line(out_file);
    END LOOP;
    CLOSE c_cur ; -- remember to close the cursor! ;)
    END;

    Hello all!
    I have a form in which a user can select a number of checkboxes that coorespond to fields in a table. After checking the desired boxes, the user can then click on a button and a variable (v_query) in a "when button pressed" trigger is populated with the text of a sql query. The trouble is, I want to incorporate the code contained in v_query into the REF cursor OPEN statement where it is expecting a sql query. The idea here is that the cursor would loop through the table fetching rows based on the select statement variable (v_query) and write them to a file using TEXT_IO(See below code). First, can this be done? Second, is there a better way to do accomplish this?
    DECLARE
    TYPE t_cur IS REF CURSOR ; -- define t_cur as a type
    c_cur t_cur ; -- define an actual variable of type t_cur
    r_emp emp%ROWTYPE ; -- PL/SQL record to hold row
    v_query VARCHAR2(2000) := 'SELECT * FROM emp' ; -- the query!
    BEGIN
    -- OPEN FILE
    out_file := Text_IO.Fopen('C:\BACHELOR\TEST.txt', 'w');
    OPEN c_cur FOR v_query ; -- v_query could contain any valid query
    LOOP
    FETCH c_cur INTO r_emp ; -- get first row from dataset
    EXIT WHEN %NOTFOUND
    --PRINT TO FILE 
              Text_IO.Put_line(out_file, r_emp);
              Text_IO.New_Line(out_file);
    END LOOP;
    CLOSE c_cur ; -- remember to close the cursor! ;)
    END;

  • What is the better approach to populate Ref cursor into ADF business Component

    HI All,
    I have a requirement where I get the search results by joining more than 10 tables for my search criteria.
    What is the best approach to populate into ADF BCs.
    I have to go with Stored Procedure approach where I input the search Criteria and get the cursor back from the same.
    If I populate VO programmatically then the filtering at column level is a challenge.
    Anyone Please help me. Thanks in Advance.
    Thanks,
    Balaji Mucheli.

    The number of tables to be joined for a VO's query shouldn't matter - if the query is valid and fixed.
    Are you saying that you have logic to decide which tables to join to create the correct query?  I admit that would be a difficult thing to do, other than with a programmatic VO.  However, there are two possible solutions for doing this without a programmatic VO.
    Instead of your procedure returning a REF CURSOR, you can create an object type (CREATE TYPE) and a nested table of that type.  Then you have a function that returns an instance of the nested table.  The query in the VO is SELECT my_column... FROM TABLE(CAST my_table_function(:bind_variable) AS my_table_type).  You may have trouble getting the VO to accept this query as valid SQL, but it IS valid and it DOES work.
    Create a VO to be the master VO - it should have all the attributes that you intend to use, but the query can be anything, even a SELECT from DUAL.  Then create other VOs that subclass the master VO - one for each major variation of the query.  When you use the VO, use the data control for the master VO to create your pages, but change the pageDef to make the VO name a variable (with expression language).  Then you can set that variable to the correct child VO for the query that needs to execute.

  • Ref cursor stopped returning values for the output.

    Hi Everyone,
    My DB version is
    BANNER                                                        
    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 - Production  
    Please do have a look at the code, and let me know where I've gone wrong, because select query is fetching data. Previously procedure was returning values too through ref cursor. Please correct me where I've gone wrong.
    create or replace
    PROCEDURE
    SPL_SPN_MISSING_EMR_AOE_DTL (IN_PATIENT_ID            NUMBER,
                                 IN_FACILITY_ID           NUMBER,
                                 IN_DRAW_DT               DATE,
                                 IN_REQUISITION_NUMBER    ORDER_REQUISITION_HEADER.REQUISITION_NUMBER%TYPE,
                                 IN_CORP_ACRONYM          CORPORATION.CORPORATION_ACRONYM%TYPE,
                                 IN_ABCDEF_MRN           PATIENT.ABCDEF_MRN%TYPE,
                                 IN_ACCOUNT_NUMBER        FACILITY_ACCOUNT_DETAIL.ACCOUNT_NUMBER%TYPE,
                                 IN_HLAB_NUM              FACILITY_ACCOUNT_DETAIL.HLAB_NUM%TYPE,
                                 OV_COMMENTS              OUT   VARCHAR2,
                                 OR_QUES_AND_ANS          OUT   SYS_REFCURSOR) AS                               
    *  Copyright (C) 2013 ABCDEF Laboratories
    *  All Rights Reserved
    *  This Work Contains Trade Secrets And Confidential Material Of
    *  ABCDEF Laboratories., And Its Use Of Disclosure In Whole Or In Part
    *  Without Express Written Permission Of ABCDEF Laboratories Is Prohibited.
    *  Company              : ABCDEF Laboratories
    *  Project              : ABCDEF Scorpion
    *  Name                 : SPL_SPN_MISSING_EMR_AOE_DTL
    * In Parameters         : In_Patient_Id            Number
    *                         In_Facility_Id           Number
    *                         In_Draw_Dt               Date
    *                         In_Requisition_Number    Order_Requisition_Header.Requisition_Number%Type,
    *                         In_Corp_Acronym          Corporation.Corporation_Acronym%Type
    *                         In_ABCDEF_Mrn           Patient.ABCDEF_Mrn%Type
    *                         In_Account_Number        Facility_Account_Detail.Account_Number%Type
    *                         In_Hlab_Num              Facility_Account_Detail.Hlab_Num%Type
    * Out Parameters        : OV_COMMENTS           Out   Varchar2
    *                         OR_QUES_AND_ANS       Out   Sys_Refcursor
    * Description           : This Procedure Will Fetch The Mising Emr Aoe Detail And Provide
    *                         Necessary Comments As Well.
    * Modification History  :
    *   Date       Version No.        Author                 Description
    * 21/01/2014      1.0            ABCDEF               Initial Version  
    * 27/01/2014      1.1            ABCDEF               Restricted the output for duplicate questions
    *                                                     and answers, partially answered AOE. Also renamed
    *                                                     the output variable names.
        CC_PACKAGE_NAME             CONSTANT VARCHAR2(50)  := 'SPL_SPN_MISSING_EMR_AOE_DTL';   
        CC_PROCEDURE_NAME           CONSTANT VARCHAR2(50)  := 'SPL_SPN_MISSING_EMR_AOE_DTL';
        VC_AVL_PAT_QUES             VARCHAR2(1000);
        VC_DUP_PAT_QUES             VARCHAR2(1000);
        VC_ACTUAL_QUES              VARCHAR2(1000);
        VC_ACTUAL_QUES_CNT          NUMBER:= 0;
        VR_QUES_AND_ANS             SYS_REFCURSOR;
        VN_AVL_PAT_QUES_CNT         NUMBER := 0;
        VN_DUP_PAT_QUES_CNT         NUMBER := 0;
        VN_EXACT_PAT_ID_CNT         NUMBER := 0;
        VN_DUPL_PAT_ID              NUMBER := 0;
        VN_EXTERNAL_ID              PATIENT.EXTERNAL_ID%TYPE;
        VC_OBX_QUES                 VARCHAR2(1000);
        VC_OBX_QUES_CNT             NUMBER := 0;
        VN_OBX_QUES_CNT             NUMBER := 0;
        PAT_EXTERNAL_ID             PATIENT.EXTERNAL_ID%TYPE;
        VC_EXACT_BOOLEAN_VAL        VARCHAR2(10) := 'FALSE';
        VC_EXACT_PAR_BOOLEAN_VAL    VARCHAR2(10) := 'FALSE';
        VC_DUPL_BOOLEAN_VAL         VARCHAR2(10) := 'FALSE';
        VC_DUPL_PAR_BOOLEAN_VAL     VARCHAR2(10) := 'FALSE';
        VC_REJECTED_BOOLEAN_VAL     VARCHAR2(10) := 'FALSE';
        VC_REJECTED_PAR_BOOLEAN_VAL VARCHAR2(10) := 'FALSE';
        VC_COMMENTS                 VARCHAR2(100);
        VC_PAR_COMMENTS             VARCHAR2(100);
        VC_RETURN_EXACT_PAT         CHAR(1) := 'N';
        VC_RETURN_DUPL_PAT          CHAR(1) := 'N';
        VC_RETURN_REJECT_PAT        CHAR(1) := 'N';
        VC_CHK_FOR_EXT_ID           CHAR(1) := 'N';
        VN_MAX_MSG_ID               INTERFACE_A04_OBX_SEGMENT.MSG_ID%TYPE;
        VN_MAX_COUNT                NUMBER := 0;
        VN_ITERATION_RUN            NUMBER := 0;
    BEGIN
       SPL_SPN_ERROR_LOGGING_SPK.INFO_PROC
                      (IC_PACKAGE_NAME    => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                      ,IC_PROCEDURE_NAME  => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                      ,IN_BATCH_ID        => '100'
                      ,IC_MESSAGE_TEXT    => 'Start of the procedure with Patient_Id:'||IN_PATIENT_ID||' Facility_Id:'||IN_FACILITY_ID||
                                             ' Draw_Dt:'||IN_DRAW_DT||' Requisition_Number:'||IN_REQUISITION_NUMBER||' Corp_Acronym:'||IN_CORP_ACRONYM||
                                             ' ABCDEF_Mrn:'||IN_ABCDEF_MRN||' Account_Number:'||IN_ACCOUNT_NUMBER||' Hlab_Num:'||IN_HLAB_NUM);
        <<AOE_TEST_LOOP>>
        FOR AOE_REC IN (SELECT ORD.TEST_ID
                            FROM ORDER_REQUISITION_DETAIL ORD
                           WHERE ORD.REQUISITION_HDR_ID = (SELECT ORH.REQUISITION_HDR_ID
                                                             FROM ORDER_REQUISITION_HEADER ORH
                                                            WHERE ORH.REQUISITION_NUMBER = IN_REQUISITION_NUMBER)
                            AND ORD.TEST_CODE IN (SELECT TEST_CODE FROM INTERFACE_ADT_AOE_MASTER WHERE SOURCE_SYSTEM = IN_CORP_ACRONYM))
            LOOP
                VN_ITERATION_RUN := VN_ITERATION_RUN + 1;
                SELECT COUNT(DISTINCT PATIENT_ID)
                INTO VN_EXACT_PAT_ID_CNT
                FROM EMR_ADTAOE_DTL
                WHERE PATIENT_ID  = IN_PATIENT_ID
                AND   TEST_ID = AOE_REC.TEST_ID
                AND   FACILITY_ID = IN_FACILITY_ID   
                AND   (DRAW_DATE   = IN_DRAW_DT
                    OR DRAW_DATE   = TO_DATE('2999/12/31','YYYY/MM/DD'))
                AND   SOURCE_SYSTEM = IN_CORP_ACRONYM ;
                --Collecting all questions in interface_adt_aoe_master
                SELECT STRAGG(SUB1.QUESTION_CODE), COUNT(SUB1.QUESTION_CODE)
                INTO VC_ACTUAL_QUES, VC_ACTUAL_QUES_CNT
                FROM (SELECT DISTINCT QUESTION_CODE FROM INTERFACE_ADT_AOE_MASTER
                      WHERE TEST_CODE = (SELECT TEST_CODE FROM TEST WHERE TEST_ID = AOE_REC.TEST_ID)
                      AND   SOURCE_SYSTEM = IN_CORP_ACRONYM
                      ORDER BY QUESTION_CODE) SUB1;
                 SPL_SPN_ERROR_LOGGING_SPK.INFO_PROC
                              (IC_PACKAGE_NAME    => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                              ,IC_PROCEDURE_NAME  => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                              ,IN_BATCH_ID        => '100'
                              ,IC_MESSAGE_TEXT    => 'vc_actual_ques:'||VC_ACTUAL_QUES ||
                                                     ' vn_exact_pat_id_cnt:'||VN_EXACT_PAT_ID_CNT||
                                                     ' aoe_rec.test_id:'||AOE_REC.TEST_ID||
                                                     ' VN_ITERATION_RUN:'||VN_ITERATION_RUN);
                <<MAIN_IF_BLOCK>>
                IF
                    VN_EXACT_PAT_ID_CNT = 1 AND
                    VN_ITERATION_RUN    >= 1 THEN               
                    --Collecting avaliable questions in emr_adtaoe_dtl               
                    SELECT STRAGG(SUB.QUESTION_CODE), COUNT(DISTINCT SUB.QUESTION_CODE)
                    INTO VC_AVL_PAT_QUES, VN_AVL_PAT_QUES_CNT
                    FROM (SELECT DISTINCT QUESTION_CODE FROM EMR_ADTAOE_DTL
                          WHERE TEST_ID = AOE_REC.TEST_ID
                          AND   PATIENT_ID  = IN_PATIENT_ID
                          AND   FACILITY_ID = IN_FACILITY_ID
                          AND   (DRAW_DATE   = IN_DRAW_DT
                              OR DRAW_DATE   = TO_DATE('2999/12/31','YYYY/MM/DD'))
                          AND   SOURCE_SYSTEM = IN_CORP_ACRONYM
                          AND   ANSWER IS NOT NULL
                          ORDER BY QUESTION_CODE) SUB;
                    SPL_SPN_ERROR_LOGGING_SPK.INFO_PROC
                      (IC_PACKAGE_NAME    => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                      ,IC_PROCEDURE_NAME  => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                      ,IN_BATCH_ID        => '100'
                      ,IC_MESSAGE_TEXT    => 'vc_avl_pat_ques:'||VC_AVL_PAT_QUES||
                                             ' vn_avl_pat_ques_cnt:'||VN_AVL_PAT_QUES_CNT);
                    <<CASE_1_AND_2>>
                    IF
                        VC_AVL_PAT_QUES = VC_ACTUAL_QUES THEN
                        VC_EXACT_BOOLEAN_VAL := 'TRUE';
                        VC_COMMENTS := 'AOE AVAILABLE';
                    ELSIF--<<case_1_and_2>>
                        (VC_AVL_PAT_QUES != VC_ACTUAL_QUES OR VC_AVL_PAT_QUES IS NULL) AND
                        VN_AVL_PAT_QUES_CNT >= 0 THEN
                        VC_EXACT_PAR_BOOLEAN_VAL := 'TRUE';
                        VC_PAR_COMMENTS := 'PARTIAL AOE AVAILABLE';
                    END IF;--<<case_1_and_2>>
                ELSIF
                    VN_EXACT_PAT_ID_CNT = 0 AND
                    VN_ITERATION_RUN    > 1 THEN 
                    VC_EXACT_PAR_BOOLEAN_VAL := 'TRUE';
                    VC_PAR_COMMENTS := 'PARTIAL AOE AVAILABLE';
                ELSIF--<<Main_if_block>>
                    VN_EXACT_PAT_ID_CNT = 0 THEN
                    <<DUPL_PAT_LOOP>>
                    FOR PAT_ID_REC IN(SELECT DISTINCT PATIENT_ID
                                      FROM PATIENT P
                                      WHERE P.ABCDEF_MRN = IN_ABCDEF_MRN
                                      AND EXISTS(SELECT 1 FROM EMR_ADTAOE_DTL EAD
                                                 WHERE EAD.PATIENT_ID  = P.PATIENT_ID
                                                 AND   EAD.TEST_ID     = AOE_REC.TEST_ID
                                                 AND   EAD.FACILITY_ID = IN_FACILITY_ID
                                                 AND  (EAD.DRAW_DATE  = IN_DRAW_DT
                                                    OR EAD.DRAW_DATE  = TO_DATE('2999/12/31','YYYY/MM/DD'))
                                                 AND   EAD.SOURCE_SYSTEM   = IN_CORP_ACRONYM)
                                      AND P.PATIENT_ID != IN_PATIENT_ID)
                    LOOP
                        --Collecting avaliable questions in emr_adtaoe_dtl
                        SELECT STRAGG(SUB.QUESTION_CODE), COUNT(QUESTION_CODE)
                        INTO VC_DUP_PAT_QUES, VN_DUP_PAT_QUES_CNT
                        FROM (SELECT QUESTION_CODE FROM EMR_ADTAOE_DTL   
                               WHERE TEST_ID     = AOE_REC.TEST_ID
                               AND   PATIENT_ID  = PAT_ID_REC.PATIENT_ID
                               AND   FACILITY_ID = IN_FACILITY_ID
                               AND   (DRAW_DATE   = IN_DRAW_DT
                                   OR DRAW_DATE   = TO_DATE('2999/12/31','YYYY/MM/DD'))
                               AND   SOURCE_SYSTEM = IN_CORP_ACRONYM
                               AND   ANSWER IS NOT NULL
                               ORDER BY QUESTION_CODE) SUB;
                        <<CASE_3_AND_4>>
                        IF 
                            VC_DUP_PAT_QUES = VC_ACTUAL_QUES THEN
                            VC_DUPL_BOOLEAN_VAL  := 'TRUE';
                            VC_COMMENTS := 'AOE AVAILABLE FOR DUPLICATE PATIENT';
                        ELSIF
                            VC_DUP_PAT_QUES != VC_ACTUAL_QUES AND
                            VN_DUP_PAT_QUES_CNT >= 0 THEN
                            VC_DUPL_PAR_BOOLEAN_VAL := 'TRUE';
                            VC_PAR_COMMENTS := 'PARTIAL AOE AVAILABLE FOR DUPLICATE PATIENT';
                        END IF;--<<case_3_and_4>>
                        VN_DUPL_PAT_ID := PAT_ID_REC.PATIENT_ID;
                        SPL_SPN_ERROR_LOGGING_SPK.INFO_PROC
                                  (IC_PACKAGE_NAME    => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                                  ,IC_PROCEDURE_NAME    => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                                  ,IN_BATCH_ID        => '100'
                                  ,IC_MESSAGE_TEXT    => 'vc_dup_pat_ques:'||VC_DUP_PAT_QUES||
                                                         ' vn_dup_pat_ques_cnt:'||VN_DUP_PAT_QUES_CNT||
                                                         ' VC_COMMENTS:'||VC_COMMENTS||
                                                         ' VC_PAR_COMMENTS:'||VC_PAR_COMMENTS);
                    END LOOP DUPL_PAT_LOOP;
                    VC_CHK_FOR_EXT_ID := 'Y';
                    IF
                      VC_CHK_FOR_EXT_ID = 'Y' THEN
                      <<EXTERNAL_ID_LOOP>>
                      FOR P_PAT_EXT_ID_REC IN (SELECT DISTINCT P.EXTERNAL_ID
                                                 FROM PATIENT P
                                                WHERE P.ABCDEF_MRN = IN_ABCDEF_MRN
                                                  AND P.EXTERNAL_ID IS NOT NULL)
                      LOOP 
                          INSERT INTO TT_A04_OBX_QUES_ANS_DTL
                          (SELECT IAOBX.MSG_ID, IAOBX.OBSERVATION_IDENTIFIER, IAOBX.OBSERVATION_VALUE, IAM.UOM
                            FROM INTERFACE_A04_OBX_SEGMENT IAOBX, INTERFACE_ADT_AOE_MASTER IAM
                            WHERE IAOBX.OBSERVATION_IDENTIFIER = IAM.QUESTION_CODE
                            AND   (IAOBX.OBSERVATION_DTM  = TO_CHAR(IN_DRAW_DT,'YYYYMMDD')
                                OR IAOBX.OBSERVATION_DTM = TO_CHAR(TO_DATE('2999/12/31','YYYY/MM/DD'),'YYYYMMDD'))
                            AND   IAOBX.MSG_ID IN (SELECT IPID.MSG_ID
                                                     FROM   INTERFACE_A04_PID_SEGMENT IPID
                                                    WHERE   IPID.PATIENT_ID_EXTERNAL  = P_PAT_EXT_ID_REC.EXTERNAL_ID
                                                      AND   IPID.MSG_ID IN (SELECT IMSH.MSG_ID
                                                                             FROM  INTERFACE_A04_MSH_SEGMENT IMSH
                                                                             WHERE (TRIM('W' FROM SUBSTR(IMSH.SENDING_FACILITY,5,LENGTH(IMSH.SENDING_FACILITY))) = IN_ACCOUNT_NUMBER
                                                                                 OR SUBSTR(IMSH.SENDING_FACILITY,2,LENGTH(IMSH.SENDING_FACILITY))    = IN_HLAB_NUM))));
                          BEGIN
                            SELECT STRAGG(SUB3.OBSERVATION_IDENTIFIER), COUNT(OBSERVATION_IDENTIFIER)
                            INTO VC_OBX_QUES, VC_OBX_QUES_CNT
                            FROM (SELECT DISTINCT OBSERVATION_IDENTIFIER
                                  FROM TT_A04_OBX_QUES_ANS_DTL
                                  ORDER BY OBSERVATION_IDENTIFIER)SUB3;
                             IF
                                VC_OBX_QUES = VC_ACTUAL_QUES THEN
                                VC_COMMENTS := 'AOE RECEIVED IN A REJECTED ADT';
                                VC_REJECTED_BOOLEAN_VAL := 'TRUE';
                             ELSIF
                                VC_OBX_QUES != VC_ACTUAL_QUES AND
                                VC_OBX_QUES_CNT > 0 THEN
                                VC_PAR_COMMENTS := 'PARTIAL AOE RECEIVED IN A REJECTED ADT';
                                VC_REJECTED_PAR_BOOLEAN_VAL := 'TRUE';
                             END IF;
                            VN_EXTERNAL_ID := P_PAT_EXT_ID_REC.EXTERNAL_ID;
                        EXCEPTION
                          WHEN NO_DATA_FOUND THEN
                            VC_REJECTED_BOOLEAN_VAL := 'FALSE';
                            VC_REJECTED_PAR_BOOLEAN_VAL := 'FALSE';
                        END;
                         SPL_SPN_ERROR_LOGGING_SPK.INFO_PROC
                                    (IC_PACKAGE_NAME    => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                                    ,IC_PROCEDURE_NAME    => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                                    ,IN_BATCH_ID        => '100'
                                    ,IC_MESSAGE_TEXT    => 'vc_obx_ques:'||VC_OBX_QUES||
                                                           ' vc_obx_ques_cnt:'||VC_OBX_QUES_CNT);
                      END LOOP EXTERNAL_ID_LOOP;
                    END IF;
                END IF;--<<Main_if_block>>
          END LOOP AOE_TEST_LOOP;
      --Returning output as per the execution result.
      IF
         VC_EXACT_BOOLEAN_VAL = 'TRUE' AND
         VC_EXACT_PAR_BOOLEAN_VAL = 'FALSE' THEN
         OV_COMMENTS := VC_COMMENTS;
         VC_DUPL_BOOLEAN_VAL         := NULL;
         VC_DUPL_PAR_BOOLEAN_VAL     := NULL;
         VC_REJECTED_BOOLEAN_VAL     := NULL;
         VC_REJECTED_PAR_BOOLEAN_VAL := NULL;
         VC_RETURN_EXACT_PAT := 'Y';
      ELSIF
         --VC_EXACT_BOOLEAN_VAL = 'TRUE' AND
         VC_EXACT_PAR_BOOLEAN_VAL = 'TRUE' THEN
         OV_COMMENTS := VC_PAR_COMMENTS;
         VC_DUPL_BOOLEAN_VAL         := NULL;
         VC_DUPL_PAR_BOOLEAN_VAL     := NULL;
         VC_REJECTED_BOOLEAN_VAL     := NULL;
         VC_REJECTED_PAR_BOOLEAN_VAL := NULL;
         VC_RETURN_EXACT_PAT := 'Y';
      END IF;
      IF
        VC_RETURN_EXACT_PAT = 'Y' THEN
        --Returning result set (OV_COMMENTS,Question and Answer) for the exact patient.(Case 1 (AOE) and 2 (PARTIAL AOE))
        SELECT MAX (SUB.COUNT_QUES_ANS)
        INTO VN_MAX_COUNT FROM (SELECT COUNT(*) OVER (PARTITION BY EAD.QUESTION_CODE, EAD.ANSWER) AS COUNT_QUES_ANS
                                FROM  EMR_ADTAOE_DTL EAD , INTERFACE_ADT_AOE_MASTER IAM, TEST T
                                WHERE T.TEST_ID = EAD.TEST_ID
                                AND   IAM.TEST_CODE = T.TEST_CODE
                                AND   EAD.SOURCE_SYSTEM = IAM.SOURCE_SYSTEM
                                AND   EAD.QUESTION_CODE = IAM.QUESTION_CODE
                                AND   EAD.PATIENT_ID    = IN_PATIENT_ID
                                AND   EAD.FACILITY_ID   = IN_FACILITY_ID
                                AND   (TRUNC(EAD.DRAW_DATE)   = IN_DRAW_DT
                                      OR TRUNC(EAD.DRAW_DATE) = TRUNC(TO_DATE('12-31-2999','mm-dd-yyyy')))
                                AND   EAD.SOURCE_SYSTEM = IN_REQUISITION_NUMBER) SUB;
         IF
            VN_MAX_COUNT > 1 THEN
            SPL_SPN_ERROR_LOGGING_SPK.INFO_PROC
                                    (IC_PACKAGE_NAME    => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                                    ,IC_PROCEDURE_NAME  => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                                    ,IN_BATCH_ID        => '100'
                                    ,IC_MESSAGE_TEXT    => 'exact patient duplicate scenario'||' vn_max_count:'||VN_MAX_COUNT);
            OPEN VR_QUES_AND_ANS FOR                                 
            SELECT DISTINCT IAM.QUESTION_CODE,
                  (SELECT DISTINCT CASE
                                   WHEN EAD.ANSWER IS NULL THEN NULL
                                   WHEN LENGTH(TRIM(TRANSLATE(EAD.ANSWER, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', ' '))) IS NULL THEN EAD.ANSWER
                                   ELSE TO_CHAR(TRUNC(EAD.ANSWER *  DECODE(UPPER(IAM.UOM), 'KGS', 2.20462,1),2))
                                   END
                    FROM  EMR_ADTAOE_DTL EAD , TEST T
                    WHERE T.TEST_ID = EAD.TEST_ID
                    AND   IAM.TEST_CODE = T.TEST_CODE
                    AND   EAD.SOURCE_SYSTEM = IAM.SOURCE_SYSTEM
                    AND   EAD.QUESTION_CODE = IAM.QUESTION_CODE
                    AND   EAD.PATIENT_ID    = IN_PATIENT_ID
                    AND   EAD.FACILITY_ID   = IN_FACILITY_ID
                    AND   (TRUNC(EAD.DRAW_DATE)    = IN_DRAW_DT
                            OR TRUNC(EAD.DRAW_DATE) = TRUNC(TO_DATE('12-31-2999','mm-dd-yyyy')))
                    AND   EAD.SOURCE_SYSTEM = IN_CORP_ACRONYM
                    AND   EAD.ANSWER IS NOT NULL
                    AND   EAD.STATUS = DECODE(IAM.MATCH_TYPE, 'AT', EAD.STATUS, 'N')
                    ) AS ANSWER
            FROM INTERFACE_ADT_AOE_MASTER IAM
            WHERE IAM.SOURCE_SYSTEM = IN_CORP_ACRONYM
            AND IAM.TEST_CODE IN  (SELECT ORD.TEST_CODE
                                     FROM ORDER_REQUISITION_DETAIL ORD
                                    WHERE ORD.REQUISITION_HDR_ID = (SELECT ORH.REQUISITION_HDR_ID
                                                                      FROM ORDER_REQUISITION_HEADER ORH
                                                                     WHERE ORH.REQUISITION_NUMBER = IN_REQUISITION_NUMBER)   
                                    AND EXISTS (SELECT 1 FROM EMR_ADTAOE_DTL EAD1, INTERFACE_ADT_AOE_MASTER IAM1, TEST T1
                                                 WHERE  ORD.TEST_ID = EAD1.TEST_ID
                                                  AND   IAM1.TEST_CODE = T1.TEST_CODE
                                                  AND   EAD1.SOURCE_SYSTEM = IAM1.SOURCE_SYSTEM
                                                  AND   EAD1.QUESTION_CODE = IAM1.QUESTION_CODE
                                                  AND   EAD1.PATIENT_ID    = IN_PATIENT_ID
                                                  AND   EAD1.FACILITY_ID   = IN_FACILITY_ID
                                                  AND   (TRUNC(EAD1.DRAW_DATE)    = IN_DRAW_DT
                                                        OR TRUNC(EAD1.DRAW_DATE) = TRUNC(TO_DATE('12-31-2999','mm-dd-yyyy')))
                                                  AND   EAD1.SOURCE_SYSTEM = IN_CORP_ACRONYM
                                                  AND   EAD1.ANSWER IS NOT NULL
                                                  AND   EAD1.STATUS = DECODE(IAM1.MATCH_TYPE, 'AT', EAD1.STATUS, 'N')));
         ELSIF
           VN_MAX_COUNT = 1 THEN
           SPL_SPN_ERROR_LOGGING_SPK.INFO_PROC
                                    (IC_PACKAGE_NAME    => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                                    ,IC_PROCEDURE_NAME  => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                                    ,IN_BATCH_ID        => '100'
                                    ,IC_MESSAGE_TEXT    => 'exact patient unique scenario'||' vn_max_count:'||VN_MAX_COUNT);
           OPEN VR_QUES_AND_ANS FOR                                 
           SELECT DISTINCT IAM.QUESTION_CODE,
                  (SELECT DISTINCT CASE
                                   WHEN EAD.ANSWER IS NULL THEN NULL
                                   WHEN LENGTH(TRIM(TRANSLATE(EAD.ANSWER, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', ' '))) IS NULL THEN EAD.ANSWER
                                   ELSE TO_CHAR(TRUNC(EAD.ANSWER *  DECODE(UPPER(IAM.UOM), 'KGS', 2.20462,1),2))
                                   END
                    FROM  EMR_ADTAOE_DTL EAD , TEST T
                    WHERE T.TEST_ID = EAD.TEST_ID
                    AND   IAM.TEST_CODE = T.TEST_CODE
                    AND   EAD.SOURCE_SYSTEM = IAM.SOURCE_SYSTEM
                    AND   EAD.QUESTION_CODE = IAM.QUESTION_CODE
                    AND   EAD.PATIENT_ID    = IN_PATIENT_ID
                    AND   EAD.FACILITY_ID   = IN_FACILITY_ID
                    AND   (TRUNC(EAD.DRAW_DATE)    = IN_DRAW_DT
                            OR TRUNC(EAD.DRAW_DATE) = TRUNC(TO_DATE('12-31-2999','mm-dd-yyyy')))
                    AND   EAD.SOURCE_SYSTEM = IN_CORP_ACRONYM
                    AND   EAD.ANSWER IS NOT NULL
                    AND   EAD.STATUS = DECODE(IAM.MATCH_TYPE, 'AT', EAD.STATUS, 'N')
                    ) AS ANSWER
            FROM INTERFACE_ADT_AOE_MASTER IAM
            WHERE IAM.SOURCE_SYSTEM = IN_CORP_ACRONYM
            AND IAM.TEST_CODE IN  (SELECT ORD.TEST_CODE
                                     FROM ORDER_REQUISITION_DETAIL ORD
                                    WHERE ORD.REQUISITION_HDR_ID = (SELECT ORH.REQUISITION_HDR_ID
                                                                      FROM ORDER_REQUISITION_HEADER ORH
                                                                     WHERE ORH.REQUISITION_NUMBER = IN_REQUISITION_NUMBER));
         END IF;                           
         OR_QUES_AND_ANS := VR_QUES_AND_ANS;
        SPL_SPN_ERROR_LOGGING_SPK.INFO_PROC
                      (IC_PACKAGE_NAME    => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                      ,IC_PROCEDURE_NAME  => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                      ,IN_BATCH_ID        => '100'
                      ,IC_MESSAGE_TEXT    => 'vc_exact_boolean_val:'||VC_EXACT_BOOLEAN_VAL||
                                             ' vc_exact_par_boolean_val:'||VC_EXACT_PAR_BOOLEAN_VAL||
                                             ' OV_COMMENTS:'||OV_COMMENTS);
      END IF;               
      IF
          VC_DUPL_BOOLEAN_VAL = 'TRUE' AND
          VC_DUPL_PAR_BOOLEAN_VAL = 'FALSE' THEN
          OV_COMMENTS := VC_COMMENTS;
          VC_EXACT_BOOLEAN_VAL        := NULL;
          VC_EXACT_PAR_BOOLEAN_VAL    := NULL;
          VC_REJECTED_BOOLEAN_VAL     := NULL;
          VC_REJECTED_PAR_BOOLEAN_VAL := NULL;
          VC_RETURN_DUPL_PAT := 'Y';
      ELSIF
         --VC_DUPL_BOOLEAN_VAL = 'TRUE' AND
         VC_DUPL_PAR_BOOLEAN_VAL = 'TRUE' THEN
         OV_COMMENTS := VC_PAR_COMMENTS;
         VC_EXACT_BOOLEAN_VAL        := NULL;
         VC_EXACT_PAR_BOOLEAN_VAL    := NULL;
         VC_REJECTED_BOOLEAN_VAL     := NULL;
         VC_REJECTED_PAR_BOOLEAN_VAL := NULL;
         VC_RETURN_DUPL_PAT := 'Y';
      END IF;
      IF
        VC_RETURN_DUPL_PAT = 'Y' THEN
        --Returning result set (OV_COMMENTS,Question and Answer) for the duplicate patient.(Case 3 (AOE) and 4 (PARTIAL AOE))
        SELECT MAX (SUB.COUNT_QUES_ANS)
        INTO VN_MAX_COUNT FROM (SELECT COUNT(*) OVER (PARTITION BY EAD.QUESTION_CODE, EAD.ANSWER) AS COUNT_QUES_ANS
                                FROM  EMR_ADTAOE_DTL EAD , INTERFACE_ADT_AOE_MASTER IAM, TEST T
                                WHERE T.TEST_ID = EAD.TEST_ID
                                AND   IAM.TEST_CODE = T.TEST_CODE
                                AND   EAD.SOURCE_SYSTEM = IAM.SOURCE_SYSTEM
                                AND   EAD.QUESTION_CODE = IAM.QUESTION_CODE
                                AND   EAD.PATIENT_ID    = VN_DUPL_PAT_ID
                                AND   EAD.FACILITY_ID   = IN_FACILITY_ID
                                AND   (TRUNC(EAD.DRAW_DATE)   = IN_DRAW_DT
                                      OR TRUNC(EAD.DRAW_DATE) = TRUNC(TO_DATE('12-31-2999','mm-dd-yyyy')))
                                AND   EAD.SOURCE_SYSTEM = IN_REQUISITION_NUMBER) SUB;
         IF
            VN_MAX_COUNT > 1 THEN
            SPL_SPN_ERROR_LOGGING_SPK.INFO_PROC
                                    (IC_PACKAGE_NAME    => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                                    ,IC_PROCEDURE_NAME  => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                                    ,IN_BATCH_ID        => '100'
                                    ,IC_MESSAGE_TEXT    => 'duplicate patient duplicate scenario'||' vn_max_count:'||VN_MAX_COUNT);
            OPEN VR_QUES_AND_ANS FOR                                 
            SELECT DISTINCT IAM.QUESTION_CODE,
                  (SELECT DISTINCT CASE
                                   WHEN EAD.ANSWER IS NULL THEN NULL
                                   WHEN LENGTH(TRIM(TRANSLATE(EAD.ANSWER, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', ' '))) IS NULL THEN EAD.ANSWER
                                   ELSE TO_CHAR(TRUNC(EAD.ANSWER *  DECODE(UPPER(IAM.UOM), 'KGS', 2.20462,1),2))
                                   END
                    FROM  EMR_ADTAOE_DTL EAD , TEST T
                    WHERE T.TEST_ID = EAD.TEST_ID
                    AND   IAM.TEST_CODE = T.TEST_CODE
                    AND   EAD.SOURCE_SYSTEM = IAM.SOURCE_SYSTEM
                    AND   EAD.QUESTION_CODE = IAM.QUESTION_CODE
                    AND   EAD.PATIENT_ID    = VN_DUPL_PAT_ID
                    AND   EAD.FACILITY_ID   = IN_FACILITY_ID
                    AND   (TRUNC(EAD.DRAW_DATE)    = IN_DRAW_DT
                            OR TRUNC(EAD.DRAW_DATE) = TRUNC(TO_DATE('12-31-2999','mm-dd-yyyy')))
                    AND   EAD.SOURCE_SYSTEM = IN_CORP_ACRONYM
                    AND   EAD.ANSWER IS NOT NULL
                    AND   EAD.STATUS = DECODE(IAM.MATCH_TYPE, 'AT', EAD.STATUS, 'N')
                    ) AS ANSWER
            FROM INTERFACE_ADT_AOE_MASTER IAM
            WHERE IAM.SOURCE_SYSTEM = IN_CORP_ACRONYM
            AND IAM.TEST_CODE IN  (SELECT ORD.TEST_CODE
                                     FROM ORDER_REQUISITION_DETAIL ORD
                                    WHERE ORD.REQUISITION_HDR_ID = (SELECT ORH.REQUISITION_HDR_ID
                                                                      FROM ORDER_REQUISITION_HEADER ORH
                                                                     WHERE ORH.REQUISITION_NUMBER = IN_REQUISITION_NUMBER)   
                                    AND EXISTS (SELECT 1 FROM EMR_ADTAOE_DTL EAD1, INTERFACE_ADT_AOE_MASTER IAM1, TEST T1
                                                 WHERE  ORD.TEST_ID = EAD1.TEST_ID
                                                  AND   IAM1.TEST_CODE = T1.TEST_CODE
                                                  AND   EAD1.SOURCE_SYSTEM = IAM1.SOURCE_SYSTEM
                                                  AND   EAD1.QUESTION_CODE = IAM1.QUESTION_CODE
                                                  AND   EAD1.PATIENT_ID    = VN_DUPL_PAT_ID
                                                  AND   EAD1.FACILITY_ID   = IN_FACILITY_ID
                                                  AND   (TRUNC(EAD1.DRAW_DATE)    = IN_DRAW_DT
                                                        OR TRUNC(EAD1.DRAW_DATE) = TRUNC(TO_DATE('12-31-2999','mm-dd-yyyy')))
                                                  AND   EAD1.SOURCE_SYSTEM = IN_CORP_ACRONYM
                                                  AND   EAD1.ANSWER IS NOT NULL
                                                  AND   EAD1.STATUS = DECODE(IAM1.MATCH_TYPE, 'AT', EAD1.STATUS, 'N')));
         ELSIF
           VN_MAX_COUNT = 1 THEN
            SPL_SPN_ERROR_LOGGING_SPK.INFO_PROC
                                    (IC_PACKAGE_NAME    => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                                    ,IC_PROCEDURE_NAME  => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                                    ,IN_BATCH_ID        => '100'
                                    ,IC_MESSAGE_TEXT    => 'duplicate patient unique scenario'||' vn_max_count:'||VN_MAX_COUNT);
            OPEN VR_QUES_AND_ANS FOR                                 
            SELECT DISTINCT IAM.QUESTION_CODE,
                  (SELECT DISTINCT CASE
                                   WHEN EAD.ANSWER IS NULL THEN NULL
                                   WHEN LENGTH(TRIM(TRANSLATE(EAD.ANSWER, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', ' '))) IS NULL THEN EAD.ANSWER
                                   ELSE TO_CHAR(TRUNC(EAD.ANSWER *  DECODE(UPPER(IAM.UOM), 'KGS', 2.20462,1),2))
                                   END
                    FROM  EMR_ADTAOE_DTL EAD , TEST T
                    WHERE T.TEST_ID = EAD.TEST_ID
                    AND   IAM.TEST_CODE = T.TEST_CODE
                    AND   EAD.SOURCE_SYSTEM = IAM.SOURCE_SYSTEM
                    AND   EAD.QUESTION_CODE = IAM.QUESTION_CODE
                    AND   EAD.PATIENT_ID    = VN_DUPL_PAT_ID
                    AND   EAD.FACILITY_ID   = IN_FACILITY_ID
                    AND   (TRUNC(EAD.DRAW_DATE)    = IN_DRAW_DT
                            OR TRUNC(EAD.DRAW_DATE) = TRUNC(TO_DATE('12-31-2999','mm-dd-yyyy')))
                    AND   EAD.SOURCE_SYSTEM = IN_CORP_ACRONYM
                    AND   EAD.ANSWER IS NOT NULL
                    AND   EAD.STATUS = DECODE(IAM.MATCH_TYPE, 'AT', EAD.STATUS, 'N')
                    ) AS ANSWER
            FROM INTERFACE_ADT_AOE_MASTER IAM
            WHERE IAM.SOURCE_SYSTEM = IN_CORP_ACRONYM
            AND IAM.TEST_CODE IN  (SELECT ORD.TEST_CODE
                                     FROM ORDER_REQUISITION_DETAIL ORD
                                    WHERE ORD.REQUISITION_HDR_ID = (SELECT ORH.REQUISITION_HDR_ID
                                                                      FROM ORDER_REQUISITION_HEADER ORH
                                                                     WHERE ORH.REQUISITION_NUMBER = IN_REQUISITION_NUMBER));
         END IF; 
        OR_QUES_AND_ANS := VR_QUES_AND_ANS;
        SPL_SPN_ERROR_LOGGING_SPK.INFO_PROC
                      (IC_PACKAGE_NAME    => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                      ,IC_PROCEDURE_NAME  => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                      ,IN_BATCH_ID        => '100'
                      ,IC_MESSAGE_TEXT    => 'vc_dup_pat_ques:'||VC_DUP_PAT_QUES||
                                             ' vc_dupl_boolean_val:'||VC_DUPL_BOOLEAN_VAL||
                                             ' vc_dupl_par_boolean_val:'||VC_DUPL_PAR_BOOLEAN_VAL||
                                             ' OV_COMMENTS:'||OV_COMMENTS);
      END IF;               
      IF
         VC_REJECTED_BOOLEAN_VAL = 'TRUE' AND
         VC_REJECTED_PAR_BOOLEAN_VAL = 'FALSE' THEN
         OV_COMMENTS := VC_COMMENTS;
         VC_EXACT_BOOLEAN_VAL        := NULL;
         VC_EXACT_PAR_BOOLEAN_VAL    := NULL;
         VC_DUPL_BOOLEAN_VAL         := NULL;
         VC_DUPL_PAR_BOOLEAN_VAL     := NULL;
         VC_RETURN_REJECT_PAT := 'Y';
      ELSIF
         --VC_REJECTED_BOOLEAN_VAL = 'FALSE' AND
         VC_REJECTED_PAR_BOOLEAN_VAL = 'TRUE' THEN
         OV_COMMENTS := VC_PAR_COMMENTS;
         VC_EXACT_BOOLEAN_VAL        := NULL;
         VC_EXACT_PAR_BOOLEAN_VAL    := NULL;
         VC_DUPL_BOOLEAN_VAL         := NULL;
         VC_DUPL_PAR_BOOLEAN_VAL     := NULL;
         VC_RETURN_REJECT_PAT := 'Y';
      ELSIF
         VC_REJECTED_BOOLEAN_VAL = 'FALSE' AND
         VC_REJECTED_PAR_BOOLEAN_VAL = 'FALSE' THEN
         --Returning result set (OV_COMMENTS) for the rejected ADT.(Case 7)
         OV_COMMENTS := 'AOE NOT RECEIVED IN ADT';
         OR_QUES_AND_ANS := NULL;
         SPL_SPN_ERROR_LOGGING_SPK.INFO_PROC
                        (IC_PACKAGE_NAME    => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                        ,IC_PROCEDURE_NAME  => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                        ,IN_BATCH_ID        => '100'
                        ,IC_MESSAGE_TEXT    => 'vc_obx_ques:'||VC_OBX_QUES||
                                               ' vc_rejected_boolean_val:'||VC_REJECTED_BOOLEAN_VAL||
                                               ' vc_rejected_par_boolean_val:'||VC_REJECTED_PAR_BOOLEAN_VAL||
                                               ' OV_COMMENTS:'||OV_COMMENTS);
         VC_EXACT_BOOLEAN_VAL        := NULL;
         VC_EXACT_PAR_BOOLEAN_VAL    := NULL;
         VC_DUPL_BOOLEAN_VAL         := NULL;
         VC_DUPL_PAR_BOOLEAN_VAL     := NULL;
      END IF;
      IF
        VC_RETURN_REJECT_PAT = 'Y' THEN
        --Returning result set (OV_COMMENTS,Question and Answer) for the rejected ADT.(Case 5 (AOE) and 6 (PARTIAL AOE))
        --In case of multiple external id with same patient, facility and draw date; the lastest record should be picked.
        SELECT MAX(MSG_ID) INTO VN_MAX_MSG_ID FROM TT_A04_OBX_QUES_ANS_DTL;
        OPEN VR_QUES_AND_ANS FOR
        SELECT DISTINCT IAM.QUESTION_CODE,
                       (SELECT DISTINCT
                         CASE
                            WHEN TOBX.OBSERVATION_VALUE IS NULL THEN NULL
                            WHEN LENGTH(TRIM(TRANSLATE(TOBX.OBSERVATION_VALUE, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', ' '))) IS NULL THEN TOBX.OBSERVATION_VALUE
                            ELSE TO_CHAR(TRUNC(TOBX.OBSERVATION_VALUE *  DECODE(UPPER(TOBX.UOM), 'KGS', 2.20462,1),2))
                         END
                         FROM TT_A04_OBX_QUES_ANS_DTL TOBX
                        WHERE TOBX.OBSERVATION_IDENTIFIER = IAM.QUESTION_CODE
                          AND TOBX.MSG_ID = VN_MAX_MSG_ID) AS ANSWER
         FROM INTERFACE_ADT_AOE_MASTER IAM
        WHERE SOURCE_SYSTEM = IN_CORP_ACRONYM;
        OR_QUES_AND_ANS := VR_QUES_AND_ANS;
        SPL_SPN_ERROR_LOGGING_SPK.INFO_PROC
                        (IC_PACKAGE_NAME    => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                        ,IC_PROCEDURE_NAME  => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                        ,IN_BATCH_ID        => '100'
                        ,IC_MESSAGE_TEXT    => 'vc_rejected_boolean_val:'||VC_REJECTED_BOOLEAN_VAL||
                                               ' vc_rejected_par_boolean_val:'||VC_REJECTED_PAR_BOOLEAN_VAL||
                                               ' OV_COMMENTS:'||OV_COMMENTS);
      END IF;
       SPL_SPN_ERROR_LOGGING_SPK.INFO_PROC
                        (IC_PACKAGE_NAME    => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                        ,IC_PROCEDURE_NAME  => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                        ,IN_BATCH_ID        => '100'
                        ,IC_MESSAGE_TEXT    => 'End of the procedure with Patient_Id:'||IN_PATIENT_ID||' Facility_Id:'||IN_FACILITY_ID||
                                               ' Draw_Dt:'||IN_DRAW_DT||' Requisition_Number:'||IN_REQUISITION_NUMBER||' Corp_Acronym:'||IN_CORP_ACRONYM||
                                               ' ABCDEF_Mrn:'||IN_ABCDEF_MRN||' Account_Number:'||IN_ACCOUNT_NUMBER||' Hlab_Num:'||IN_HLAB_NUM);
    EXCEPTION
      WHEN NO_DATA_FOUND THEN
        SPL_SPN_ERROR_LOGGING_SPK.ERROR_PROC
                        (IC_PACKAGE_NAME    => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                        ,IC_PROCEDURE_NAME  => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                        ,IN_BATCH_ID        => '100'
                        ,IC_MESSAGE_TEXT    => SQLERRM);
      WHEN OTHERS THEN
        SPL_SPN_ERROR_LOGGING_SPK.ERROR_PROC
                        (IC_PACKAGE_NAME    => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                        ,IC_PROCEDURE_NAME  => 'SPL_SPN_MISSING_EMR_AOE_DTL'
                        ,IN_BATCH_ID        => '100'
                        ,IC_MESSAGE_TEXT    => SQLERRM);
    END SPL_SPN_MISSING_EMR_AOE_DTL;
    Regards,
    BS2012.

    Hey Guys,
    I'm sorry, that I troubled you all. But I found the issue and solved it.
    The actual problem is residing at that max of that partition by query. I had a misconception that this query will always return a value which is positive number like 1,2 etc.
    But sometimes it's returning null as well. So the ref cursor is fetching nothing. Now I've modified my code and everything is working fine. Thanks for your help and support.
    Regards,
    BS2012.

  • Odd error while opening a ref cursor

    Hi.
    I have a procedure in a package that has both in and out parameters. One of those out parameters is a ref cursor. The procedure creates a dynamic query and then executes it, then it opens the cursor:
    PROCEDURE PROC(
    A IN VARCHAR2,
    B IN VARCHAR2,
    C OUT TYPES.cursorType; --(TYPES is a package whose only use is to declare a cursor type)
    ) IS
    --DECLARATIONS
    OPEN C FOR 'SELECT A, B, C, D...';
    END;
    When I execute the package in an anonymous block it throws the error:
    ORA-00938: not enough arguments for function, just in the line where the cursor is being opened.
    Any ideas?

    is everything defined correctly?
    create or replace package types  as
      type cursorType is ref cursor;
    end types;
    SQL> set serveroutput on
    SQL> declare
      2 
      3    ref_C types.cursorType;
      4   
      5    v_a varchar2(1);
      6    v_b varchar2(1);
      7    v_c varchar2(1);
      8    v_d varchar2(1);
      9   
    10    procedure Proc (a in varchar2
    11                   ,b in varchar2
    12                   ,C out types.cursorType) as
    13 
    14      begin
    15        open C for 'select :1, :2, ''c'', ''d'' from dual' using a, b;
    16    end  Proc;
    17  begin
    18 
    19 
    20    Proc('a', 'b', ref_C);
    21   
    22    fetch ref_C into v_a, v_b, v_c, v_d;
    23    if (ref_C%found) then
    24      dbms_output.put_line(v_a);
    25      dbms_output.put_line(v_b);
    26      dbms_output.put_line(v_c);
    27      dbms_output.put_line(v_d);
    28    end if;
    29   
    30   
    31  end;
    32  /
    a
    b
    c
    dP;
    Edited by: bluefrog on Feb 18, 2010 6:07 PM

  • Ref Cursor and For Loop

    The query below will return values in the form of
    bu     seq     eligible
    22     2345     Y
    22     2345     N
    22     1288     N
    22     1458     Y
    22     1458     N
    22     1234     Y
    22     1333     N
    What I am trying to accomplish is to loop through the records returned.
    for each seq if there is a 'N' in the eligible column return no record for that seq
    eg seq 2345 has 'Y' and 'N' thus no record should be returned.
    seq 1234 has only a 'Y' then return the record
    seq 1333 has 'N' so return no record.
    How would I accomplish this with a ref Cursor and pass the values to the front end application.
    Procedure InvalidNOs(io_CURSOR OUT T_CURSOR)
         IS
              v_CURSOR T_CURSOR;
         BEGIN
    OPEN v_CURSOR FOR
    '     select bu, seq, eligible ' ||
    '     from (select bu, seq, po, tunit, tdollar,eligible,max(eligible) over () re ' ||
    '          from (select bu, seq, po, tunit, tdollar,eligible ' ||
    '          from ( ' ||
    '          select bu, seq, po, tunit, tdollar, eligible, sum(qty) qty, sum(price*qty) dollars ' ||
    '               from ' ||
    '               ( select /*+ use_nl(t,h,d,s) */ ' ||
    '               h.business_unit_id bu, h.edi_sequence_id seq, d.edi_det_sequ_id dseq, ' ||
    '                    s.edi_size_sequ_id sseq, h.po_number po, h.total_unit tUnit, h.total_amount tDollar, ' ||
    '                    s.quantity qty, s.unit_price price,' ||
    '               (select (case when count(*) = 0 then ''Y'' else ''N'' end) ' ||
    '          from sewn.NT_edii_po_det_error ' ||
    '          where edi_det_sequ_id = d.edi_det_sequ_id ' ||
    '               ) eligible ' ||
    '     from sewn.nt_edii_purchase_size s, sewn.nt_edii_purchase_det d, ' ||
    '     sewn.nt_edii_purchase_hdr h, sewn.nt_edii_param_temp t ' ||
    '     where h.business_unit_id = t.business_unit_id ' ||
    '     and h.edi_sequence_id = t.edi_sequence_id ' ||
    '     and h.business_unit_id = d.business_unit_id ' ||
    '     and h.edi_sequence_id = d.edi_sequence_id ' ||
    '     and d.business_unit_id = s.business_unit_id ' ||
    '     and d.edi_sequence_id = s.edi_sequence_id ' ||
    '     and d.edi_det_sequ_id = s.edi_det_sequ_id ' ||
    '     ) group by bu, seq, po, tunit, tdollar, eligible ' ||
    '     ) ' ||
    '     group by bu, seq, po, tunit, tdollar, eligible)) ';
              io_CURSOR := v_CURSOR;
    END     InvalidNOs;

    One remark why you should not use the assignment between ref cursor
    variables.
    (I remembered I saw already such thing in your code).
    Technically you can do it but it does not make sense and it can confuse your results.
    In the opposite to usual variables, when your assignment copies value
    from one variable to another, cursor variables are pointers to the memory.
    Because of this when you assign one cursor variable to another you just
    duplicate memory pointers. You don't copy result sets. What you do for
    one pointer is that you do for another and vice versa. They are the same.
    I think the below example is self-explained:
    SQL> /* usual variables */
    SQL> declare
      2   a number;
      3   b number;
      4  begin
      5   a := 1;
      6   b := a;
      7   a := a + 1;
      8   dbms_output.put_line('a = ' || a);
      9   dbms_output.put_line('b = ' || b);
    10  end;
    11  /
    a = 2
    b = 1
    PL/SQL procedure successfully completed.
    SQL> /* cursor variables */
    SQL> declare
      2   a sys_refcursor;
      3   b sys_refcursor;
      4  begin
      5   open a for select empno from emp;
      6   b := a;
      7   close b;
      8 
      9   /* next action is impossible - cursor already closed */
    10   /* a and b are the same ! */
    11   close a;
    12  end;
    13  /
    declare
    ERROR at line 1:
    ORA-01001: invalid cursor
    ORA-06512: at line 11
    SQL> declare
      2   a sys_refcursor;
      3   b sys_refcursor;
      4   vempno emp.empno%type;
      5 
      6  begin
      7   open a for select empno from emp;
      8   b := a;
      9 
    10   /* Fetch first row from a */
    11   fetch a into vempno;
    12   dbms_output.put_line(vempno);
    13 
    14   /* Fetch from b gives us SECOND row, not first -
    15      a and b are the SAME */
    16 
    17   fetch b into vempno;
    18   dbms_output.put_line(vempno);
    19 
    20 
    21  end;
    22  /
    7369
    7499
    PL/SQL procedure successfully completed.Rgds.
    Message was edited by:
    dnikiforov

  • Dynamic sql and ref cursors URGENT!!

    Hi,
    I'm using a long to build a dynamic sql statement. This is limited by about 32k. This is too short for my statement.
    The query results in a ref cursor.
    Does anyone have an idea to create larger statement or to couple ref cursors, so I can execute the statement a couple of times and as an result I still have one ref cursor.
    Example:
    /* Determine if project is main project, then select all subprojects */
    for i in isMainProject loop
    if i.belongstoprojectno is null then
    for i in ProjectSubNumbers loop
    if ProjectSubNumbers%rowcount=1 then
    SqlStatement := InitialStatement || i.projectno;
    else
    SqlStatement := SqlStatement || PartialStatement || i.projectno;
    end if;
    end loop;
    else
    for i in ProjectNumber loop
    if ProjectNumber%rowcount=1 then
    SqlStatement := InitialStatement || i.projectno;
    else
    SqlStatement := SqlStatement || PartialStatement || i.projectno;
    end if;
    end loop;
    end if;
    end loop;
    /* Open ref cursor */
    open sql_output for SqlStatement;
    Thanks in advance,
    Jeroen Muis
    KCI Datasystems BV
    mailto:[email protected]

    Example for 'dynamic' ref cursor - dynamic WHERE
    (note that Reports need 'static' ref cursor type
    for building Report Layout):
    1. Stored package
    CREATE OR REPLACE PACKAGE report_dynamic IS
    TYPE type_ref_cur_sta IS REF CURSOR RETURN dept%ROWTYPE; -- for Report Layout only
    TYPE type_ref_cur_dyn IS REF CURSOR;
    FUNCTION func_dyn (p_where VARCHAR2) RETURN type_ref_cur_dyn;
    END;
    CREATE OR REPLACE PACKAGE BODY report_dynamic IS
    FUNCTION func_dyn (p_where VARCHAR2) RETURN type_ref_cur_dyn IS
    ref_cur_dyn type_ref_cur_dyn;
    BEGIN
    OPEN ref_cur_dyn FOR
    'SELECT * FROM dept WHERE ' | | NVL (p_where, '1 = 1');
    RETURN ref_cur_dyn;
    END;
    END;
    2. Query PL/SQL in Reports
    function QR_1RefCurQuery return report_dynamic.type_ref_cur_sta is
    begin
    return report_dynamic.func_dyn (:p_where);
    end;
    Regards
    Zlatko Sirotic
    null

  • ORA-01008 with ref cursor and dynamic sql

    When I run the follwing procedure:
    variable x refcursor
    set autoprint on
    begin
      Crosstab.pivot(p_max_cols => 4,
       p_query => 'select job, count(*) cnt, deptno, row_number() over (partition by job order by deptno) rn from scott.emp group by job, deptno',
       p_anchor => Crosstab.array('JOB'),
       p_pivot  => Crosstab.array('DEPTNO', 'CNT'),
       p_cursor => :x );
    end;I get the following error:
    ^----------------
    Statement Ignored
    set autoprint on
    begin
    adsmgr.Crosstab.pivot(p_max_cols => 4,
    p_query => 'select job, count(*) cnt, deptno, row_number() over (partition by
    p_anchor => adsmgr.Crosstab.array('JOB'),
    p_pivot => adsmgr.Crosstab.array('DEPTNO', 'CNT'),
    p_cursor => :x );
    end;
    ORA-01008: not all variables bound
    I am running this on a stored procedure as follows:
    create or replace package Crosstab
    as
        type refcursor is ref cursor;
        type array is table of varchar2(30);
        procedure pivot( p_max_cols       in number   default null,
                         p_max_cols_query in varchar2 default null,
                         p_query          in varchar2,
                         p_anchor         in array,
                         p_pivot          in array,
                         p_cursor in out refcursor );
    end;
    create or replace package body Crosstab
    as
    procedure pivot( p_max_cols          in number   default null,
                     p_max_cols_query in varchar2 default null,
                     p_query          in varchar2,
                     p_anchor         in array,
                     p_pivot          in array,
                     p_cursor in out refcursor )
    as
        l_max_cols number;
        l_query    long;
        l_cnames   array;
    begin
        -- figure out the number of columns we must support
        -- we either KNOW this or we have a query that can tell us
        if ( p_max_cols is not null )
        then
            l_max_cols := p_max_cols;
        elsif ( p_max_cols_query is not null )
        then
            execute immediate p_max_cols_query into l_max_cols;
        else
            RAISE_APPLICATION_ERROR(-20001, 'Cannot figure out max cols');
        end if;
        -- Now, construct the query that can answer the question for us...
        -- start with the C1, C2, ... CX columns:
        l_query := 'select ';
        for i in 1 .. p_anchor.count
        loop
            l_query := l_query || p_anchor(i) || ',';
        end loop;
        -- Now add in the C{x+1}... CN columns to be pivoted:
        -- the format is "max(decode(rn,1,C{X+1},null)) cx+1_1"
        for i in 1 .. l_max_cols
        loop
            for j in 1 .. p_pivot.count
            loop
                l_query := l_query ||
                    'max(decode(rn,'||i||','||
                               p_pivot(j)||',null)) ' ||
                                p_pivot(j) || '_' || i || ',';
            end loop;
        end loop;
        -- Now just add in the original query
        l_query := rtrim(l_query,',')||' from ( '||p_query||') group by ';
        -- and then the group by columns...
        for i in 1 .. p_anchor.count
        loop
            l_query := l_query || p_anchor(i) || ',';
        end loop;
        l_query := rtrim(l_query,',');
        -- and return it
        execute immediate 'alter session set cursor_sharing=force';
        open p_cursor for l_query;
        execute immediate 'alter session set cursor_sharing=exact';
    end;
    end;
    /I can see from the error message that it is ignoring the x declaration, I assume it is because it does not recognise the type refcursor from the procedure.
    How do I get it to recognise this?
    Thank you in advance

    Thank you for your help
    This is the version of Oracle I am running, so this may have something to do with that.
    Oracle9i Enterprise Edition Release 9.2.0.8.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.8.0 - Production
    I found this on Ask Tom (http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:3027089372477)
    Hello, Tom.
    I have one bind variable in a dynamic SQL expression.
    When I open cursor for this sql, it gets me to ora-01008.
    Please consider:
    Connected to:
    Oracle8i Enterprise Edition Release 8.1.7.4.1 - Production
    JServer Release 8.1.7.4.1 - Production
    SQL> declare
      2    type cur is ref cursor;
      3    res cur;
      4  begin
      5    open res for
      6    'select * from (select * from dual where :p = 1) connect by 1 = 1'
      7    using 1;
      8  end;
      9  /
    declare
    ERROR at line 1:
    ORA-01008: not all variables bound
    ORA-06512: at line 5
    SQL> declare
      2    type cur is ref cursor;
      3    res cur;
      4  begin
      5    open res for
      6    'select * from (select * from dual where :p = 1) connect by 1 = 1'
      7    using 1, 2;
      8  end;
      9  /
    PL/SQL procedure successfully completed.
    And if I run the same thing on 10g -- all goes conversely. The first part runs ok, and the second
    part reports "ORA-01006: bind variable does not exist" (as it should be, I think). Remember, there
    is ONE bind variable in sql, not two. Is it a bug in 8i?
    What should we do to avoid this error running the same plsql program code on different Oracle
    versions?
    P.S. Thank you for your invaluable work on this site.
    Followup   June 9, 2005 - 6pm US/Eastern:
    what is the purpose of this query really?
    but it would appear to be a bug in 8i (since it should need but one).  You will have to work that
    via support. I changed the type to tarray to see if the reserved word was causing a problem.
    variable v_refcursor refcursor;
    set autoprint on;
    begin 
         crosstab.pivot (p_max_cols => 4,
                 p_query => 
                   'SELECT job, COUNT (*) cnt, deptno, ' || 
                   '       ROW_NUMBER () OVER ( ' || 
                   '          PARTITION BY job ' || 
                   '          ORDER BY deptno) rn ' || 
                   'FROM   emp ' ||
                   'GROUP BY job, deptno',
                   p_anchor => crosstab.tarray ('JOB'),
                   p_pivot => crosstab.tarray ('DEPTNO', 'CNT'),
                   p_cursor => :v_refcursor);
    end;
    /Was going to use this package as a stored procedure in forms but I not sure it's going to work now.

  • Ref cursors and dynamic sql..

    I want to be able to use a fuction that will dynamically create a SQL statement and then open a cursor based on that SQL statement and return a ref to that cursor. To achieve that, I am trying to build the sql statement in a varchar2 variable and using that variable to open the ref cursor as in,
    open l_stmt for refcurType;
    where refcurType is a strong ref cursor. I am unable to do so because I get an error indication that I can not use strong ref cursor type. But, if I can not use a strong ref cursor, I will not be able to use it to build the report based on the ref cursor because Reports 9i requires strong ref cursors to be used. Does that mean I can not use dynamic sql with Reports 9i ref cursors? Else, how I can do that? Any documentation available?

    Philipp,
    Thank you for your reply. My requirement is that, sometimes I need to construct a whole query based on some input, and sometimes not. But the output record set would be same and the layout would be more or less same. I thought ref cursor would be ideal. Ofcourse, I could do this without dynamic SQL by writing the SQL multiple times if needed. But, I think dynamic SQL is a proper candidate for this case. Your suggestion to use lexical variable is indeed a good alternative. In effect, if needed, I could generate an entire SQL statement and place in some place holder (like &stmt) and use it as a static SQL query in my data model. In that case, why would one ever need ref cursor in reports? Is one more efficient over the other? My guess is, in the lexical variable case, part of the processing (like parsing) is done on the app server while in a function based ref cursor, the entire process takes place in the DB server and there is probably a better chance for re-use(?)
    Thanks,
    Murali.

  • Ref cursor and dynamic sql

    Hi..
    I'm using a ref cursor query to fetch data for a report and works just fine. However i need to use dynamic sql in the query because the columns used in the where condition and for some calculations may change dynamically according to user input from the form that launches the report..
    Ideally the query should look like this:
    select
    a,b,c
    from table
    where :x = something
    and :y = something
    and (abs(:x/:y........)
    The user should be able to switch between :x and :y
    Is there a way to embed dynamic sql in a ref cursor query in Reports 6i?
    Reports 6i
    Forms 6i
    Windows 2000 PRO

    Hello Nicola,
    You can parameterize your ref cursor by putting the query's select statement in a procedure/function (defined in your report, or in the database), and populating it based on arguments accepted by the procedure.
    For example, the following procedure accepts a strongly typed ref cursor and populates it with emp table data based on the value of the 'mydept' input parameter:
    Procedure emp_refcursor(emp_data IN OUT emp_rc, mydept number) as
    Begin
    -- Open emp_data for select all columns from emp where deptno = mydept;
    Open emp_data for select * from emp where deptno = mydept;
    End;
    This procedure/function can then be called from the ref cursor query program unit defined in your report's data model, to return the filled ref cursor to Reports.
    Thanks,
    The Oracle Reports Team.

  • Ref Cursor over Implicit and explicit cursors

    Hi,
    In my company when writing PL/SQL procedure, everyone uses "Ref Cursor",
    But the article below, says Implicit is best , then Explicit and finally Ref Cursor..
    [http://www.oracle-base.com/forums/viewtopic.php?f=2&t=10720]
    I am bit confused by this, can any one help me to understand this?
    Thanks

    SeshuGiri wrote:
    In my company when writing PL/SQL procedure, everyone uses "Ref Cursor",
    But the article below, says Implicit is best , then Explicit and finally Ref Cursor..
    [http://www.oracle-base.com/forums/viewtopic.php?f=2&t=10720]
    I am bit confused by this, can any one help me to understand this?There is performance and there is performance...
    To explain. There is only a single type of cursor in Oracle - that is the cursor that is parsed and compiled by the SQL engine and stored in the database's shared pool. The "+client+" is then given a handle (called a SQL Statement Handle in many APIs) that it can use to reference that cursor in the SQL engine.
    The performance of this cursor is not determined by the client. It is determined by the execution plan and how much executing that cursor cost ito server resources.
    The client can be Java, Visual Basic, .Net - or a PL/SQL program. This client language (a client of SQL), has its own structures in dealing with that cursor handle received from the SQL engine.
    It can hide it from the developer all together - so that he/she does not even see that there is a statement handle. This is what implicit cursors are in PL/SQL.
    It can allow the developer to manually define the cursor structure - this is what explicit cursors, ref cursors, and DBMS_SQL cursors are in PL/SQL.
    Each of these client cursor structures provides the programmer with a different set of features to deal with SQL cursor. Explicit cursor constructs in PL/SQL do not allow for the use of dynamic SQL. Ref cursors and DBMS_SQL cursors do. Ref cursors do not allow the programmer to determine, at run-time, the structure of the SQL projection of the cursor. DBMS_SQL cursors do.
    Only ref cursors can be created in PL/SQL and then be handed over to another client (e.g. Java/VB) for processing. Etc.
    So each of the client structures/interfaces provides you with a different feature set for SQL cursors.
    Choosing implicit cursors for example does not make the SQL cursor go faster. The SQL engine does not know and does not care, what client construct you are using to deal with the SQL cursor handle it gave you. It does not matter. It does not impact its SQL cursor performance.
    But on the client side, it can matter - as your code in dealing with that SQL cursor determines how fast your interaction with that SQL cursor is. How many context switches you make. How effectively you use and re-use the SQL (e.g. hard parsing vs soft parsing vs re-using the same cursor handle). Etc.
    Is there any single client cursor construct that is better? No.
    That is an ignorant view. The client language provides a toolbox, where each tool has a specific application. The knowledgeable developer will use the right tool for the job. The idiot developer will select one tool and use it as The Hammer to "solve" all the problems.

Maybe you are looking for

  • How to change the description of a program or report

    Hi, I had copy a report of and changed thereby the name. But the description is still the same and I can't find a way to change this. The problem with the description is that it appears as program-title in selection-screen-->select-options. Thanks fo

  • Mass Creation of Variants

    I have hundreds of products that all have the same variant configurations, and I understandably don't want to pay someone to manually go through the WebTools interface to create all the variants.  After looking through the WebTools database, I am pla

  • How to Know the changes made on a program and complete activity on it

    Hi abapers, I want to know who is working on a particular report currently and check the complete activity like changes made on the report. Is there any transaction to check this, please let me know Thanks in advance Bond

  • Does the iphone 4s have a chip

    does the iphone 4s have a chip

  • Is there new n95 firmware

    hey guys i got a txt today from my nokia is there an update or not ive not checked but its for the n95-1 im sure 21 is the latest any ideas thanks and sorry if this has been asked already J Nokia N95 v31.0.017 16GB Nokia N91 4GB Nokia N80 2GB Sony Er