Ref cursor argument in where clause

Env: ORCL 9.2
I have a func that uses the parameters in a where clause and returns a ref cursor as result. That works fine.
I want to create an overloaded func that replaces one argument with a ref cursor. (instead of accepting a single value as an argument I want to accept multiple values) Can you specify the ref cursor in a where clause with out looping through the cursor ?
CURRENT
func(arg1,arg2,arg3) returns ref cursor
is
select blah from sometable s
where s.a = arg1
and s.b = arg2
and s.c = arg3
NEW
func(ref_cur_arg1,arg2,arg3) returns ref cursor
is
select blah from sometable s
where s.a = ref_cur_arg1
and s.b = arg2
and s.c = arg3
is there something like:
where s.a in (loop fetch ref_cur_arg1 end loop)
thx

Thanks Rich,
That's pretty much what I came up with:
FUNCTION f_bond_price_w_bb_stat (
                              p_id_ref gtyp_instr_id_ref,
                              p_price_srce bond_price.PRICE_SRCE%type,
                              p_price_type bond_price.PRICE_TYPE%type,
                              p_price_date bond_price.PRICE_DATE%type)
RETURN gtyp_bondprice_w_bb_stat_rfc
IS
lv_bondprice_rfc gtyp_bondprice_w_bb_stat_rfc;
TYPE ARRAY1 IS TABLE OF instr_ext_id_map.ext_id_value%TYPE INDEX BY BINARY_INTEGER;
t_instr_id ARRAY1;
instr_ids INSTR_EXT_ID_T := INSTR_EXT_ID_T();
BEGIN
     --suck the contents of the ref cursor into a local virtual tmp table
FETCH p_id_ref BULK COLLECT INTO t_instr_id;
FOR i IN 1..t_instr_id.COUNT LOOP
     instr_ids.extend;
          instr_ids(instr_ids.count) := t_instr_id(i);
END LOOP;
CLOSE p_id_ref;
OPEN lv_bondprice_rfc FOR
SELECT
bs.ID_ISIN,
bs.TICKER,
bs.CPN,
bs.MATURITY,
round(months_between(bs.MATURITY,sysdate)/12,1),
bs.ISSUER_INDUSTRY,
bs.INDUSTRY_SECTOR,
FROM bond_price b,
instr_ext_id_map ext,
etl.mdy_ratingstatic mrs,
     etl.mdy_extid mxid,
     etl.bloomberg_static bs
WHERE b.INSTR_ID = ext.instr_id
AND bs.ID_ISIN(+) = ext.ext_id_value
AND bs.ID_ISIN = mxid.EXTIDVALUE(+)
AND mrs.MOODYDEBTNUM(+) = mxid.MOODYDEBTNUM
AND ext.ext_id_value in (select * from TABLE (cast (instr_ids AS INSTR_EXT_ID_T) ))
AND b.PRICE_SRCE = p_price_srce
AND b.PRICE_TYPE = p_price_type
AND b.PRICE_DATE = p_price_date
RETURN lv_bondprice_rfc;
END f_bond_price_w_bb_stat;

Similar Messages

  • How to create a procedure to output REF CURSOR with any WHERE clause?

    I have an requirement like this: I have huge query which need to reuse in my code more than 10 times. This SQL has about 50 lines. Thing is for those 10 odd times sometimes the WHERE clause changes (columns are the same). So I cannot create a view since SQL is not static.
    I thought of writing a procedure with a WHERE_CLAUSE input para. I output a sys refcursor by adding the where clause. But I can't do it since you cannot add a where clause like that.
    i.e.
    PROCEDURE dynamyic_query (p_where_clause IN VARCHAR2, p_out_query OUT SYS_REFCURSOR ) IS
    BEGIN
      OPEN p_out_query FOR SELECT ......... FROM table WHERE || ' ' || p_where_clause;
    END;The above gives error.
    How to handle a situation like this???? Any help would be greatly appreciated.

    I tried this method:
    I created a table tab_test which has these records:
    TNAME                          TABTYPE    CLUSTERID                                                                                                                                                                  
    ABS_V4_P_ERROR_MESSAGES        TABLE                                                                                                                                                                                  
    ABS_V4_P_ORG_PARAM             TABLE                                                                                                                                                                                  
    ABS_V4_P_PARAMETER             TABLE                                                                                                                                                                                  
    ABS_V4_P_SYS_PARAM             TABLE                                                                                                                                                                                  
    ACCINTERFACE_PARAMETERS        TABLE                                                                                                                                                                                  
    ACCOUNTS                       TABLE                                                                                                                                                                                  
    ACCOUNT_EXTRACT_PERIODS        TABLE                                                                                                                                                                                  
    ACCOUNT_EXTRACT_PERIODS#       TABLE                                                                                                                                                                                  
    ACCOUNT_EXTRACT_PERIODS_1      TABLE                                                                                                                                                                                   Now I create this proc:
    PROCEDURE FORMS_TEXT_DYN_SQL_TEST(p_where_cluase IN VARCHAR2, p_out_cursor OUT SYS_REFCURSOR) IS
      v_stmt VARCHAR2(1000);
    BEGIN
      v_stmt := 'SELECT tname FROM tab_test WHERE tname LIKE ''%ABS_V4%'' AND tabtype = :x';
      OPEN p_out_cursor FOR v_stmt using p_where_cluase;
    END;I create this code block and run it:
    declare
      v_tname varchar2(200);
      out_cursor sys_refcursor;
    begin
      forms_text_dyn_sql_test('TABLE', out_cursor );
      LOOP
        fetch out_cursor INTO v_tname;
        exit when out_cursor%NOTFOUND;
        DBMS_OUTPUT.PUT_LINE(v_tname);
      END LOOP;
    end;
    /I get correct output:
    ABS_V4_P_ERROR_MESSAGES
    ABS_V4_P_ORG_PARAM
    ABS_V4_P_PARAMETER
    ABS_V4_P_SYS_PARAMHowever, when I change the proc like this:
    PROCEDURE FORMS_TEXT_DYN_SQL_TEST(p_where_cluase IN VARCHAR2, p_out_cursor OUT SYS_REFCURSOR) IS
      v_stmt VARCHAR2(1000);
    BEGIN
      v_stmt := 'SELECT tname FROM tab_test WHERE tname LIKE ''%ABS_V4%'' AND :y';
      OPEN p_out_cursor FOR v_stmt using p_where_cluase;
    END;And run this code block:
    declare
      v_tname varchar2(200);
      out_cursor sys_refcursor;
    begin
      forms_text_dyn_sql_test(' 1 = 1 ', out_cursor );
      LOOP
        fetch out_cursor INTO v_tname;
        exit when out_cursor%NOTFOUND;
        DBMS_OUTPUT.PUT_LINE(v_tname);
      END LOOP;
    end;
    /I get error:
    [1]: (Error): ORA-00920: invalid relational operator ORA-06512: at "ABS.FORMS_TEXT_DYN_SQL_TEST", line 6 ORA-06512: at line 5Looks like you can only put column_name = :z, column_name = :y type values. You cannot it seems replace it with any WHERE CLAUSE????

  • 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;

  • Can pipelined functions' return values be used in WHERE clause?

    If I have function MY_FUNC that returns a REFCURSOR with columns COL1, COL2, COL3
    can I use the values returned in the output cursor in my WHERE clause as well as in the SELECT clause?
    e.g.
    SELECT COL1, COL2, COL3
    FROM TABLE(MY_FUNC(param1, param2))
    WHERE COL1 = 24 AND COL2=25
    Would that be proper SQL?

    Hi,
    SQL> Create OR Replace Package Pkg_Test_ Is
      2 
      3     Type my_typ Is Table Of Number;
      4 
      5     Function fnc_test Return my_typ Pipelined;
      6 
      7  End;
      8  /
    Package created
    SQL> Create OR Replace Package Body Pkg_Test_ Is
      2 
      3     Function fnc_test Return my_typ
      4        Pipelined Is
      5        va_typ my_typ := my_typ();
      6     Begin
      7        For i IN 1 .. 10 Loop
      8           va_typ.Extend;
      9           va_typ(va_typ.Count) := i;
    10           Pipe Row(va_typ(va_typ.Count));
    11        End Loop;
    12        Return;
    13     End;
    14 
    15  End;
    16  /
    Package body created
    SQL> SELECT *
      2    FROM Table(PKG_TEST_.FNC_TEST)
      3   WHERE COLUMN_VALUE > 5
      4  /
    COLUMN_VALUE
               6
               7
               8
               9
              10Regards,
    Christian Balz

  • Ref Cursor to VB

    I have seen the many examples in this forum of returning a ref cursor to VB, where the cursor is an out parameter of the pl/sql procedure. I have that working using ADO.
    I would rather have a pl/sql function that returns a ref cursor, but have been unable to make that work on the VB side. Is this even possible?
    I have details of my code attempts here if interested:
    http://asktom.oracle.com/pls/ask/f?p=4950:8:8405510044531699984::NO::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:498045385849

    dear ashish,
    i saw your request and Iam sending u the code which i generated now
    /*type this script to create the package in scott/tiger schema*/
    /*ensure that you have the dept table in the scott/tiger schema*/
    CREATE OR REPLACE PACKAGE DEPT_DATA AS
    TYPE DEPTCURTYP IS REF CURSOR RETURN DEPT%ROWTYPE;
    PROCEDURE OPEN_DEPT_CV(DEPT_cV IN OUT DEPTCURTYP);
    END DEPT_DATA;
    CREATE OR REPLACE PACKAGE BODY DEPT_DATA AS
    PROCEDURE OPEN_DEPT_CV(DEPT_CV IN OUT DEPTCURTYP) IS
    BEGIN
    OPEN DEPT_CV FOR SELECT * FROM DEPT;
    END OPEN_DEPT_CV;
    END DEPT_DATA;
    SQL> VARIABLE VARDEPTCV REFCURSOR;
    SQL> EXECUTE DEPT_DATA.OPEN_DEPT_CV(:VARDEPTCV);
    PL/SQL procedure successfully completed.
    SQL> PRINT VARDEPTCV;
    DEPTNO DNAME LOC
    10 ACCOUNTING NEW YORK
    20 RESEARCH DALLAS
    30 SALES CHICAGO
    40 OPERATIONS BOSTON
    SQL> print vardeptcv
    now open vb6.open a form and type the following after the creating a button */
    Option Explicit
    Dim con As New ADODB.Connection
    Dim rs As New ADODB.Recordset
    Dim cmd As New ADODB.Command
    Private Sub Command1_Click()
    Set rs = cmd.Execute
    MsgBox (rs.Fields(1))
    rs.close
    cmd.close
    End Sub
    Private Sub Form_Load()
    con.ConnectionString = "Provider=MSDAORA.1;Password= TIGER; User ID=scott;Data Source=shanu;Persist Security Info=False"
    con.Open
    cmd.ActiveConnection = con
    cmd.CommandType = adCmdStoredProc
    cmd.CommandText = "dept_data.open_dept_cv"
    End Sub
    wish u all the best
    [email protected]

  • Using ref cursor in where clause

    I have a stored procedure (package procedure) that returns a ref cursor as a parameter. This procedure performs a query and returns the cursor. The procedure calls another stored procedure within the package. This second procedure also returns a ref cursor. I want to do my query on the results of the cursor returned by the second procedure. Hopefully the example below is okay.. "I had to change names to protect the blah blah...."
    For example:
    TYPE out_cursor IS REF CURSOR;
    TYPE IDTable IS TABLE OF table1.ID%TYPE;
    PROCEDURE A
    v_ID IN NUMBER,
    v_Param2 IN NUMBER,
    v_FromClause IN VARCHAR2, -- ignore for now
    v_WhereClause IN VARCHAR2, -- ignore for now
    v_retval OUT NUMBER,
    the_cursor OUT out_cursor
    IS
    v_SQLString VARCHAR2(2048);
    v_cursor1 out_cursor;
    v_tabIDs IDTable;
    BEGIN
    v_SQLString := '';
    packageA.procedureA(v_ID, v_retval, v_cursor1);
    -- this does not work
    -- I get ORA-00942: table or view does not exist
    v_SQLString := 'select distinct * from v_cursor1';
    -- I found this on the message board but
    -- it did not compile.
    -- local collection types not allowed in SQL statements
    FETCH v_cTSFiles BULK COLLECT INTO v_tabIDs;
    v_SQLString := 'select distinct * from table1 WHERE table1.ID in (select * from table(v_tabIDs))';
    OPEN the_cursor FOR v_SQLString;
    END;

    You can use that second technique but as the error message says, "local collection types not allowed in SQL statements". You need to create a schema type instead.
    [sql]
    create or replace type ttab_number is table of number
    create or replace procedure p is
    tab_id ttab_number;
    refcur sys_refcursor;
    begin
    open refcur for
    select user_id
    from all_users;
    fetch refcur bulk collect into tab_id;
    close refcur;
    for rec in (
    select *
    from all_users
    where user_id in (
    select *
    from table(cast(tab_id as ttab_number)))
    ) loop
    dbms_output.put_line(rec.username);
    end loop;
    end;
    [sql]

  • Difference Ref cursor with/with out using clause

    Hi everyone,
    When I am using dynamic sql with USING clause ,the results are not sorted in Ascending order.
    DECLARE
    TYPE emp_refcursor IS REF CURSOR;
    emp_rc emp_refcursor;
    TYPE v_emp_id IS TABLE OF number INDEX BY PLS_INTEGER;
    TYPE v_last_name IS TABLE OF varchar2(50) INDEX BY binary_integer;
    V_empno v_emp_id;
    v_ename v_last_name;
    p_deptno number := &U_DEPTNO;
    v_limit number := 10;
    v_ordcolumn varchar2(20) := 'employee_id';
    v_stmt varchar2(1000);
    BEGIN
    v_stmt :=
    'select employee_id,last_name from employees
    where department_id = :x order by :y ';
    dbms_output.put_line(v_stmt);
    OPEN emp_rc FOR v_stmt USING p_deptno,v_ordcolumn;
    LOOP
    FETCH emp_rc BULK COLLECT INTO v_empno,v_ename LIMIT v_limit;
    EXIT WHEN v_empno.count = 0;
    FOR I IN v_empno.first .. v_empno.last
    LOOP
    dbms_output.put_line(v_empno(i)||' '||v_ename(i));
    END LOOP;
    END LOOP;
    END;
    When I use dynamic sql with out USING cluase,results are sorted in Ascending order.
    DECLARE
    TYPE emp_refcursor IS REF CURSOR;
    emp_rc emp_refcursor;
    TYPE v_emp_id IS TABLE OF number INDEX BY PLS_INTEGER;
    TYPE v_last_name IS TABLE OF varchar2(50) INDEX BY binary_integer;
    V_empno v_emp_id;
    v_ename v_last_name;
    p_deptno number := &U_DEPTNO;
    v_limit number := 10;
    v_ordcolumn varchar2(20) := 'employee_id';
    v_stmt varchar2(1000);
    BEGIN
    v_stmt :=
    'select employee_id,last_name from employees
    where department_id = '||p_deptno ||
    ' order by '||v_ordcolumn;
    dbms_output.put_line(v_stmt);
    OPEN emp_rc FOR v_stmt;
    LOOP
    FETCH emp_rc BULK COLLECT INTO v_empno,v_ename LIMIT v_limit;
    EXIT WHEN v_empno.count = 0;
    FOR I IN v_empno.first .. v_empno.last
    LOOP
    dbms_output.put_line(v_empno(i)||' '||v_ename(i));
    END LOOP;
    END LOOP;
    END;
    P.S :---- department_id (used) = 50;
    Please can some one explain why this is happening like this.
    Thanks
    Raghu
    --------------------------------------------------------------------------------

    Hi sundar,
    I am new to oracle and learning/trying to get the same output by using differnt methods,rather than using FOR LOOP ,I tried to use ref cursor with dynamic sql.I am in a belief that ref cursor's with dynamic sql are faster than FOR LOOP,irrespective of the size of data.Can you correct me if I am wrong.
    Coming back to ur reply,how should my statement look like,when using ref cursor
    with USING claus to sort data by asc/desc order.
    Thanks in advance
    Raghu

  • Problem in passing ref cursor values as parameter in where clau.Most Urgent

    Problem:
    1) I have used normal cursor (C_hubmsgid_set) with some select statement such as grouping and all.
    After executing the query it will return some resultset to the specified cursor.
    2) I am trying to use another cursor which is ref cursor but the problem is
    I want to give all the resultset based on all the conditions to the ref cursor.
    But the cursor will get only the last record due to overwriting .how to get all
    the result set in a ref cursor like
    cursor c1 is select .....
    loop
    open refcursor for
    Select * from ....where condition
    end loop
    After this the refcursor( p_sysaudithistory_cur) which should have all the resultset matched by the where condition.
    3. It should be java compatible one.
    4. I am not able to match cursor row = IN Pameter value
    Below is the query:
    CREATE OR REPLACE PROCEDURE SP_TEST_audit_history2 (
    p_start IN date,
    p_end IN date,
    p_msgcode IN varchar2,
    p_partnername IN varchar2,
    p_status IN varchar2,
    p_locationname IN varchar2,
    p_custbusunit IN varchar2,
    p_sysaudithistory_cur OUT plutotypes.ref_cursor,
    p_status1 OUT NUMBER) AS
    l_status NUMBER := 0;
    CURSOR C_hubmsgid_set IS
    SELECT DISTINCT MAX(tfm.datetime) datetime, tfm.hubmsgid
    FROM tfm_status tfm, vw_msgcode_part_locn vw
    WHERE
    tfm.datetime >= NVL(p_start, TO_DATE('01/01/1981','DD/MM/YYYY')) AND
    tfm.datetime <= NVL(p_end, TO_DATE('31/12/9999','DD/MM/YYYY')) AND
    tfm.msgcode LIKE NVL(p_msgcode,'%') AND
    vw.msgcode = tfm.msgcode
    AND vw.partnername LIKE NVL(p_partnername,'%')
    AND tfm.status LIKE NVL(p_status,'%')
    AND vw.locationname LIKE NVL(p_locationname,'%')
    AND vw.custbusunit LIKE NVL(p_custbusunit,'%')
    AND rownum < 250
    GROUP BY tfm.hubmsgid
    ORDER BY datetime DESC;
    /* Loop through the Cursor */
    BEGIN
    BEGIN
    OPEN p_sysaudithistory_cur
    FOR
    SELECT
    tfm.hubmsgid ,
    tfm.status || '-'|| nvl2(tfm.exception_id,'FAILED','OK') ,
    tfm.datetime,
    tfm.exception_id
    FROM tfm_status tfm
    WHERE tfm.hubmsgid = c_hubmsgids.hubmsgid /* here only i am getting error*/
    AND tfm.datetime = c_hubmsgids.datetime
    AND tfm.status like NVL(p_status,'%')
    and rownum =1;
    EXCEPTION
    WHEN NO_DATA_FOUND
    THEN
    l_status := 1;
    END;
    p_status1 := l_status;
    END;
    Thanks in advance
    prasanth a.s.

    Please don't post duplicate questions. All it does is clutter the forums and result in fragmented threads and duplicate responses. Please see my response in the original thread at the link below.
    Please solve this Refcursor issue PLEASE

  • Using ref cursor in "in clause" in select statement

    Hi,
    Is there any way can we use the ref cursor in the in condition of a select statement.
    Regards,
    Venkat.
    Edited by: ramanamadhav on Aug 23, 2011 11:14 AM

    ramanamadhav wrote:
    I'm sorry if I post in confusing way. I will give an example. Just see the psudo code here.
    declare
    rf_cur sys_refcursor;
    begin
    pr_test(empno,rf_cur);
    -- rf_cur returning emp names.
    select * from emp
    where empname in (ref_cusor results);-- here i want to consume my ref cursor result in the in conditions.
    end;
    Thanks &Regards,
    Venkat.No you can't do that. A ref cursor is not a set of results as you believe.
    Take a read of this article...
    {thread:id=886365}

  • How to pass strings for IN Clause in REF Cursor

    I have following query;
    SELECT 1 INTO L
    FROM test_po_apprvlines
    where '4020' between NVL(approval_cost_centre_from, '0000') and
    nvl (approval_cost_centre_to, '9999')
    and req_approval_type IN ('BUS', 'FIN') and 10500 >= approval_amount
    and NVL(req_line_type, 'X') = 'X'
    AND ROWNUM =1;
    Now the values for req_approval_type should be dynamic, based on approval_amount. If approval_amout > 10000 then
    req_approval_type should have 'BUS' and 'FIN' , other wise only 'BUS'.
    I have tried with the following code using ref cursor. But i'm not getting the result.
    Any help. The problem is how to concatenate those two values to get the result.
    in the following code, strings are not recoginised properly. Valid data exists in the table.
    DECLARE
    l_approva_type1 VARCHAR2(20) := 'FIN';
    l_approva_type2 VARCHAR2(10) := 'BUS';
    l_approva_type VARCHAR2(20) := '''FIN'''||','||'''BUS''';
    L NUMBER;
    TYPE TEST_REF IS REF CURSOR;
    cur_ref TEST_REF;
    L_str varchar2(1000) := 'SELECT 1'||
    ' FROM test_po_apprvlines'
    ||' where '||'''4020'''||' between NVL(approval_cost_centre_from, '||'''0000'''||') and nvl(approval_cost_centre_to, '|| '''9999'''||')'
    ||' and req_approval_type IN ( :bi_approva_type)'||
    ' and 10500 >= approval_amount '||
    ' and req_line_type IS NULL '||
    'AND ROWNUM =1';
    L_flg varchar2(1);
    BEGIN
    DBMS_OUTPUT.PUT_LINE (l_approva_type);
    open cur_ref for l_str USING l_approva_type;
    fetch cur_ref INTO l_flg;
    close cur_ref;
    DBMS_OUTPUT.PUT_LINE (nvl(L_flg, 'x'));
    EXCEPTION
    WHEN OTHERS THEN
    if cur_ref%isopen then
         close cur_ref;
         end if;
    DBMS_OUTPUT.PUT_LINE (SQLERRM);
    END;

    You cant "Bind" here.
    One way..
    SQL> var a refcursor
    SQL> declare
      2   str varchar2(100) := '''SALESMAN'',''ANALYST''';
      3  begin
      4   open :a for 'select ename from emp
      5                where job in ('||str||')';
      6  end;
      7  /
    PL/SQL procedure successfully completed.
    SQL> print :a
    ENAME
    WARD
    SCOTT
    Message was edited by:
            jeneesh
    Results in More parsing...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Find data where data not in ref cursor

    CREATE OR REPLACE PACKAGE types AS
    TYPE weak_ref_cursor IS REF CURSOR;
    END types;
    CREATE OR REPLACE PROCEDURE procedure_name
    (p_getname OUT types.weak_ref_cursor,
    p_tablename IN VARCHAR2, p_salary IN NUMBER)
    AS
    v_tem VARCHAR2 (4000);
    BEGIN
    v_tem := 'SELECT ENAME FROM ' || UPPER (p_tablename) || ' WHERE sal > :b_salary';
    OPEN p_getname FOR v_tem USING p_salary;
    END procedure_name;
    SQL> EXECUTE procedure_name (:g_getname, 'EMP', 2000);
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.00
    SQL> print g_getname;
    ENAME
    ALLEN
    WARD
    MARTIN
    BLAKE
    babu
    JOHN
    TURNER
    7 rows selected.
    Now i want to select data from emp table where ename not in ouput of g_getname
    Please help me

    You cannot select that data from using a query(since the program unit is procedure), instead you can write a code (anonymous pl/sql block) and retrive the records and print them using dbms_output.put_line on console.

  • Where clause in cursor

    I often have a problem with cursors and after playing around they usually work. The problem is I don't really know what I'm doing as I'm relativly new to all this! Perhaps someone can help ;)
    I have the folling code to test my cursor:
    declare
    vcrn varchar2(8) := :module_choice.crn;
    vgroup_code varchar2(10) := :module_choice.group_code;
    vclass_type varchar2(10) := :module_choice.class_type;
    i int := 0;
    cursor att_cur is
    select student_id, attended, notes
    from attendance_register
    where crn = vcrn ;
    AND group_code = vgroup_code
    AND class_type = vclass_type;
    BEGIN
    for row in att_cur loop
         i := i + 1;
    end loop;
    message(i);
    END;
    the message shows i = 0, but I know it's not. When I comment out the where clause it works.
    I guess my real question would be how do you get a where clause to work like this??
    Thanks in Advance
    Mark

    This where clause will succeed if some of the variables are null:
    where ( crn = vcrn or vcrn is null )
      AND (group_code = vgroup_code or vgroup_code is null)
      AND (class_type = vclass_type or vclass_type is null)But I am very concerned about your Char datatypes. Those trailing spaces will give you nothing but lots of grief. Unless you have a compelling reason to keep them, they should be changed to varchar2.

  • Ref cursors - 'with' clause

    I am working with a procedure which is returning a ref-cursor to a Java Call. Inside the procedure I see a statment like
    Open t_results for
    with rfq_companies AS
    select statement1),
    rfq_hierarchies AS
    select statement2),
    rfq_relnhierarchies AS
    select statement 3);
    Can anybody explain such an usage for opening a ref cursor ('WITH' clause)?. What is the effect of using this and how Java will interpret this?

    The procedure is still returning a REF CURSOR, regardless of the way the SELECT statements is created. There is no effect as far as Java is concerned.
    Read more on the WITH clause:
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_10002.htm#sthref9697
    in the section: Subquery Factoring

  • Passing where clause of cursor

    my requirement is that i want to declare a cursor but the problem is that where clause of sql statement of cursor is dynamically generated according to user clicks........ e. g. number of conditions in where clause may change.....
    so..... how can i declare the cursor...how do i pass where clause to any procedure if i write procedure or function......

    u can use for-loop cursors like this,
    for v_rec in 'select * from emp where' || ur_conditions ||'
    see oracle documentation for further help and examples

  • Where clause causing a query to slow down in a cursor

    I have a table "the_table" with about 10,000 rows and four columns (id, description, inventory, and category).
    This query returns all rows immediately:
        select id
             , description
             , inventory
        from the_table
        where category =  nvl(null, category);
    However, when it is put into a cursor, like this:
    (p_user_category is a user-defined variable which can be null if the user wants all of the rows)
        c_results  sys_refcursor;
        open c_results for
            select id
                 , description
                 , inventory
            from the_table
            where category =  nvl(p_user_category, category);
        fetch c_results into v_id, v_description, v_inventory;
        close c_results;
    then it takes five minutes to return even just one row when p_user_category is null.
    However, if I change the where clause to:
        where (p_user_category is null or category = p_user_category)
    then it returns all rows immediately.
    It started being a problem right around the time of the most recent update - I am running 11.2.0.2.0 (64-bit production).

    The optimizer is smart enough to recognise that null is null, so "nvl(null,category)" collapses to "category", and your predicate "category = nvl(null, category)" is transformed to "category is not null" (if it's allowed to be null) or simply disappears - so the SQL test is not the same as the PL/SQL run.
    In PL/SQL your manual rewrite is not logicall the same as the original unless you have declared category to be non-null because your first disjunct will allow rows with a null category to be reported, while the original query would lose them.
    Check the execution plans for the SQL and the PL/SQL versions.
    Regards
    Jonathan Lewis
    http://jonathanlewis.wordpress.com
    Now on Twitter: @jloracle

Maybe you are looking for

  • How to store India Regional language in oracle database

    Hi, Can any guide us how can we store data in Indian regional languages in Oracle database. We are using Oracle 10g. Also i need to know can we convert existing data in oracle to local language ? Thanks

  • Parsing html to tree

    Hello friends, I want to parse the html text and certain variables into a tree. eg <table><tr><td>Name: ${ACCOUNT_NAME}</td></tr> <tr><td>Phone:${ACCOUNT_PHONE}</td></tr></table> the text uptil ${ACCOUNT_NAME} is the static text and the account name

  • How do I create a 'external table' against clob

    Hi there, I have a need, where I will have multiple csv files, which I plan to load it to a temporary table using the 'external table' concept. My issue is that I will have many at the same time and I don't want to create too many tables. So is there

  • Help with vertical Spry menu

    I posted this in the general forum, but thought I'd repost here since this is more specific to Spry. I'm having issues in IE (6 & 7...surprise, surprise) with my vertical spry menu. It displays exactly the way I want it when I use Opera. I think it h

  • Is there a tutorial?

    Is there a tutorial?  I just purchased and every time I try to convert a file to PDF it tells me my trial has expire and to purchase?