Dynamic query in a loop

Greedings,
I have the following query which im trying to implement as a dynamic sql. It works fine but my only problem is that the table name will be changing everytime the user runs the query. Accounts will become financial_accounts etc. Is it possible to do that in any way?
FOR rec IN (SELECT Sum(amount) AS amount,b.acnt_code AS acnt_code
            FROM accounts@db_link a,so_budgets b
            WHERE Trim(b.acnt_code)=Trim(a.accnt_code)
            AND a.period BETWEEN 2011 AND 2012
            GROUP BY b.acnt_code) LOOP
            Dbms_Output.put_line(rec.acnt_code);
            Dbms_Output.put_line(rec.amount)
END LOOP;Thank you for any help

794018 wrote:
the only thing thats going to be changing is the from table. So change FOR cursor loop with:
declare
    v_cur sys_refcursor;
    v_acnt_code varchar2(100); -- I'll assume acnt_code is a string
    v_amount number;
begin
    open v_cur for 'SELECT Sum(amount) AS amount,b.acnt_code AS acnt_code FROM ' || from_param || ' WHERE ' || where_param;
    loop
      fetch v_cur
        into  v_amount,
              v_acnt_code;
      exit when v_cur%notfound;
      dbms_output.put_line('acnt_code = ' || v_acnt_code);
      dbms_output.put_line('amount = ' || v_amount);
    end loop;
    close v_cur;
end;
/SY.

Similar Messages

  • Using Dynamic Query in For Loop

    I have a doubt whether i can use the result from dynamic query in the for loop.
    for example,
    declare
    v_sql varchar2(1000);
    v_Id INTEGER;
    begin
    v_sql := 'select id from table1 where id in ('||v_Id||')';
    FOR i in vsql LOOP
    dbms_output.put_line(i.id);
    end loop;
    end;
    The above query is possible ?

    And here's a basic example of opening up a cursor for your dynamic query...
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2    v_sql varchar2(2000);
      3    v_cur sys_refcursor;
      4    i     emp.sal%type;
      5  begin
      6    v_sql := 'select sal from emp';
      7    open v_cur for v_sql;
      8    loop
      9      fetch v_cur into i;
    10      exit when v_cur%NOTFOUND;
    11      dbms_output.put_line('Salary: '||i);
    12    end loop;
    13* end;
    SQL> /
    Salary: 800
    Salary: 1600
    Salary: 1250
    Salary: 2975
    Salary: 1250
    Salary: 2850
    Salary: 2450
    Salary: 3000
    Salary: 5000
    Salary: 1500
    Salary: 1100
    Salary: 950
    Salary: 3000
    Salary: 1300
    PL/SQL procedure successfully completed.
    SQL>

  • Geting ORA 936 -while building dynamic query in for loop.

    HI,
    I hav written a SP and its compiled and giving me the results for the data I am quering but giving ORA936 - missing expressin and giving ORA 6512 at 2 lines. Please help me me out where I am going wrong.
    CREATE OR REPLACE TYPE LIST as VARRAY(5000) of NUMBER;
    CREATE OR REPLACE PROCEDURE test( V_id IN LIST,
    v-fdate IN DATE,
    v-tdate IN DATE,
    v_flg IN CHAR)
    AS
    TYPE opfld IS RECORD (
    FID TAB.ID%TYPE,
    FCURR TAB.CURR %TYPE,
    FCNT TAB.CNT%TYPE,
    FTOT TAB.TOT%TYPE );
    TYPE OPLIST IS REF CURSOR;
    Rc oplist;
    Edtab opfld;
    Selstr VACHAR2(200);
    Whstr1 VACHAR2(200);
    Whstr2 VACHAR2(200);
    Whstr3 VACHAR2(200);
    Whstr VACHAR2(200);
    Grpstr VACHAR2(200);
    Andstr VACHAR2(200);
    Fullstr VACHAR2(200);
    BEGIN
    Selstr := ‘SELECT col1,col2,sum(col3),sum(col4) from tab1 ’;
    Whstr1 := ‘ WHERE tdate BETWEEN TO_DATE(‘||’’’’||vfdate||’’’’||’)’;
    Whstr2: = ‘ AND TO_DATE(‘||’’’’||vtdate||’’’’||’)’;
    Whstr := whstr1||whstr2;
    Grpstr := ‘GROUP BY col1,col2’;
    IF v_flg IS NOT NULL THEN
    Whstr3 := whstr||’AND FLAG = ‘||v_flg;
    else
    Whstr3 := whstr ;
    END IF;
    FOR I IN 1..id.COUNT LOOP
    BEGIN
    Andstr := ‘ AND id =’|| v_id(i);
    Whstr := whstr3 || andstr ;
    Fullstr := selstr||whstr||grpstr;
    OPEN rc for fullstr;
    LOOP
    FETCH rc into edtab
    EXIT when rc%NOTFOUND;
    END LOOP;
    Andstr := ‘’;
    Whstr :=’’;
    END; ---BEGIN of FOR loop
    END LOOP; -- for end
    CLOSE rc;
    END; -- proc end
    Created above SP and its compiled. When I try to execute the SP with below code I am getting--
    DECLARE
    V_t LIST;
    BEGIN
    V_t:= LIST();
    V_t.EXTEND(10);
    V_t(1) := 10;
    V_t(2) := 20;
    Test(v_t,’25-APR-2012’,’30-APR-2012’,’Y’);
    END;
    The SP is building correct dynamic querry and its getting executed for id = 10 and 20, giving the correct results but though I defined only 2 ids while executing and written FOR lOOP upto ID.COUNT its building query for third time and that time its not getting id, so for the third time the last part of where clause is built like
    SELECT.....
    WHERE....
    AND id = (its taking blank here)
    GROUP BY ...;
    and thus its giving me ORA 936 missing expression and ORA 06152 at line of RECORD TYPE declaration and line of OPEN rc for fullstr;
    ERROR at line 1
    ORA 00936 misssing expresiion
    ORA 006152 at line 9
    ORA 006512 at line 87
    I hav put DBMS_OUTPUT statements @ every build of dynamic wuery and its correct. here I have not copid the code I hav typed hereso not wriiten DBMS_OUTPUT.
    I tried lot of ways redefining Andstr := ‘’;
    Whstr :=’’; after for endloop but its giving the same error. is this because I am using varray? If am providing 2 ids in anonymous block then how its building query for third blank ID value.
    Please help me out here..
    Thanks a lot..

    >
    I hav written a SP and its compiled and giving me the results for the data I am quering
    >
    Then you should have posted the one that compiles and gives you results.
    The code you posted will not compile without errors. Edit your original post and provide the corrected code.
    When you do please add \ tags on the line before and after the code to preserve formatting. See the FAQ for details.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Dynamic query in where clause while looping in an internal table.

    Hi,
    Had a small question : How can i make a dynamic query for the WHERE clause while looping at an internal table.
    i want to implement a dynamic where clause query for the below example.
    it_cfx_col is an internal table and wa_cfx_col is a work area for it_cfx_col
      DATA :
      i_cfx_col TYPE TABLE OF cfx_col,
      wa_cfx_col LIKE LINE OF i_cfx_col.
    DATA : count TYPE i VALUE 0.
    DATA : l_where_clause TYPE string,
             l_where_clause2 TYPE string,
             l_name type string.
    l_name = 'NANDANOM'.
    l_scenario = 'collaboration'.
    LOOP AT it_cfx_col INTO wa_cfx_col
    WHERE CREATED_BY = l_name
    AND SCENARIO = l_scenario.
    count = count + 1.
    some business logic implemented using the work area wa_cfx_col
    endloop.
    Now i want to write a dynamic query for the where clause.
    DATA : count TYPE i VALUE 0.
      DATA : l_where_clause TYPE string,
             l_where_clause2 TYPE string,
             l_name type string.
    l_name = 'NANDANOM'.
    l_scenario = 'collaboration'.
      l_where_clause = 'CREATED_BY = l_name'.
      l_where_clause2 = 'AND SCENARIO = l_scenario'.
    if l_scenario is not initial.
      CONCATENATE  l_where_clause l_where_clause2
      INTO l_where_clause SEPARATED BY space.
    endif.
    LOOP AT i_cfx_col INTO wa_cfx_col
    WHERE (l_where_clause).
    count = count + 1.
    some business logic implemented using the work area wa_cfx_col
    endloop.
    when i compile this i get an error message as { Statement concluding with "...(l_where_clause)" ended unexpectedly}
    Even i changed the initilization of the variable  l_where_clause2 to [ l_where_clause2 = 'AND SCENARIO = l_scenario.'. ]
    added the end of line demarkation ".", but still i got the same error message.
    Is it a limtation in ABAP that i cannot write a dynamic query for the where clause while looping at an internal table?
    Regards,
    om

    Hi savita,
    there in no such 1 limitaion in abap for dynamic query .. i think the  error meassge is only beacuse of your synatx delcartaion.
    >> LOOP AT i_cfx_col INTO wa_cfx_col
       WHERE (l_where_clause).
       count = count + 1.
    some business logic implemented using the work     area    wa_cfx_col
       endloop.
    afted delclarataion also , in the where statement you should specify both the field name and value bname
       LOOP AT i_cfx_col INTO wa_cfx_col
       WHERE l_where_clause = 'CREATED_BY = l_name' .
       count = count + 1.
    hope it helps.
    regads
    priya.

  • Dynamic Query in Loop

    My objective is similar as follows -
    declare
    v varchar2(100) := 'Select sysdate from dual';
    begin
    for rec in (v)
    loop
    message(rec.sysdate);
    end loop;
    end;
    The above statements returns the following error -
    Encountered the Symbol - LOOP when expecting one of the following -......
    Actually i am having a query, which will be created dynamically. I need to execute this query in a loop because i am having some calculation for each row.
    plz help.

    I guess you are looking for something like this:
    DECLARE
    TYPE EmpCurTyp IS REF CURSOR;
    emp_cv EmpCurTyp;
    emp_rec emp%ROWTYPE;
    sql_stmt VARCHAR2(200);
    my_job VARCHAR2(15) := 'CLERK';
    BEGIN
    sql_stmt := 'SELECT * FROM emp WHERE job = :j';
    OPEN emp_cv FOR sql_stmt USING my_job;
    LOOP
    FETCH emp_cv INTO emp_rec;
    EXIT WHEN emp_cv%NOTFOUND;
    -- process record
    END LOOP;
    CLOSE emp_cv;
    END;
    But the problem is you can not use dynamic cursors in Forms. Use this feature in a database procedure/function.

  • Single quote in dynamic query

    Hi all;
    Can u please help me on the following dynamic query code ? I know I am missing the single quote around 2 dates but could not figure out where to put it ! I have tried putting 2 or 3 quotes around 2 bind vars but to no avail.
    Want to create a dynamic query to simulate the the following:
    select
    EMPNO,ENAME,JOB,MGR,HIREDATE from emp where HIREDATE >= to_date('01/01/1981','MM/DD/YYYY') and HIREDATE <= to_date('12/31/1982','MM/DD/YYYY');
    dynamic code:
    declare
    v_q varchar2(4000);
    begin
    v_q :='select EMPNO,ENAME,JOB,MGR,HIREDATE from emp ';
    V_q := V_Q
    || 'where HIREDATE >= '
    || 'to_date(' || :P_DATE1 || ',' ||'''MM/DD/YYYY''' || ' )'
    || 'and HIREDATE <= '
    || 'to_date(' || :P_DATE2 || ',' ||'''MM/DD/YYYY''' || ' )';
    -- end the sql
    v_q := v_q ||';';
    dbms_output.put_line ('V_Q is ' || V_Q);
    end;
    Thanks.
    Zen

    declare
        v_q varchar2(4000);
        v_rec emp%rowtype;
        v_cur sys_refcursor;
    begin
        v_q :='select EMPNO,ENAME,JOB,MGR,HIREDATE from emp ';
        V_q := V_Q  || 'where HIREDATE >= to_date(:P_DATE1,''MM/DD/YYYY'') and HIREDATE <= to_date(:P_DATE2,''MM/DD/YYYY'')';
        dbms_output.put_line ('V_Q is ' || V_Q);
        open v_cur
          for v_q
          using '01/01/1981',
                '12/31/1982';
        loop
          fetch v_cur
            into v_rec.empno,
                 v_rec.ename,
                 v_rec.job,
                 v_rec.mgr,
                 v_rec.hiredate;
          exit when v_cur%notfound;
          dbms_output.put_line('empno = ' || v_rec.empno);
          dbms_output.put_line('ename = ' || v_rec.ename);
          dbms_output.put_line('job = ' || v_rec.job);
          dbms_output.put_line('mgr = ' || v_rec.mgr);
          dbms_output.put_line('hiredate = ' || to_char(v_rec.hiredate,'MM/DD/YYYY'));
          dbms_output.put_line('====================');
        end loop;
        close v_cur;
    end;
    V_Q is select EMPNO,ENAME,JOB,MGR,HIREDATE from emp where HIREDATE >=
    to_date(:P_DATE1,'MM/DD/YYYY') and HIREDATE <= to_date(:P_DATE2,'MM/DD/YYYY')
    empno = 7499
    ename = ALLEN
    job = SALESMAN
    mgr = 7698
    hiredate = 02/20/1981
    ====================
    empno = 7521
    ename = WARD
    job = SALESMAN
    mgr = 7698
    hiredate = 02/22/1981
    ====================
    empno = 7566
    ename = JONES
    job = MANAGER
    mgr = 7839
    hiredate = 04/02/1981
    ====================
    empno = 7654
    ename = MARTIN
    job = SALESMAN
    mgr = 7698
    hiredate = 09/28/1981
    ====================
    empno = 7698
    ename = BLAKE
    job = MANAGER
    mgr = 7839
    hiredate = 05/01/1981
    ====================
    empno = 7782
    ename = CLARK
    job = MANAGER
    mgr = 7839
    hiredate = 06/09/1981
    ====================
    empno = 7839
    ename = KING
    job = PRESIDENT
    mgr =
    hiredate = 11/17/1981
    ====================
    empno = 7844
    ename = TURNER
    job = SALESMAN
    mgr = 7698
    hiredate = 09/08/1981
    ====================
    empno = 7900
    ename = JAMES
    job = CLERK
    mgr = 7698
    hiredate = 12/03/1981
    ====================
    empno = 7902
    ename = FORD
    job = ANALYST
    mgr = 7566
    hiredate = 12/03/1981
    ====================
    empno = 7934
    ename = MILLER
    job = CLERK
    mgr = 7782
    hiredate = 01/23/1982
    ====================
    PL/SQL procedure successfully completed.
    SQL> SY.

  • Dynamic Query Doubt

    Hi,
    I need to write a Dynamic Query to get the data from the table by using the Input date parameters.
    LIke,
    SELECT* from table where date_start between to_date('12-14-2004','mm-dd-yyyy') AND
    to_date('12-15-2005','mm-dd-yyyy');
    How can i write the above query in dynamic sql as i will get the two dates as input in my procedure
    Help me in this

    Or more preferably use bind variables with the
    EXECUTE IMMEDIATE as, if the query will be called
    many times, the bind variables will prevent hard
    parsing of the statement each time (i.e. it will be
    quicker to execute).blushadow,
    Yes, the execute immediate using bind variables is better/faster than not using bind variables, but your first example outperforms your second one. This is due to the fact that execute immediate really closes all cursors, and in your first example the cursors are kept open (yes, even though you issue a CLOSE cur_test) in the PL/SQL cursor cache.
    SQL> create table i_links
      2  as
      3  select sysdate - l linkdate from (select level l from dual connect by level <= 10000)
      4  /
    Tabel is aangemaakt.
    SQL> exec dbms_stats.gather_table_stats(user,'I_LINKS')
    PL/SQL-procedure is geslaagd.
    SQL> create or replace procedure test1 (start_date in date, end_date in date) as
      2    CURSOR cur_test IS
      3      SELECT count(*)
      4      FROM   i_links
      5      WHERE  linkdate BETWEEN start_date AND end_date;
      6    v_count NUMBER;
      7  begin
      8    OPEN cur_test;
      9    FETCH cur_test INTO v_count;
    10    CLOSE cur_test;
    11    --DBMS_OUTPUT.PUT_LINE('Count: '||v_count);
    12  end;
    13  /
    Procedure is aangemaakt.
    SQL> create or replace procedure test2 (start_date in date, end_date in date) as
      2    v_count NUMBER;
      3  begin
      4    EXECUTE IMMEDIATE 'SELECT count(*) FROM i_links WHERE linkdate BETWEEN :x1 AND :x2' INTO v_count USING start_date, end_date;
      5    --DBMS_OUTPUT.PUT_LINE('Count: '||v_count);
      6  end;
      7  /
    Procedure is aangemaakt.
    SQL> begin
      2    -- warm up
      3    test1(sysdate-365,sysdate);
      4    test2(sysdate-365,sysdate);
      5    -- begin test
      6    runstats_pkg.rs_start;
      7    for i in 1..1000
      8    loop
      9      test1(sysdate-365,sysdate);
    10    end loop;
    11    runstats_pkg.rs_middle;
    12    for i in 1..1000
    13    loop
    14      test2(sysdate-365,sysdate);
    15    end loop;
    16    runstats_pkg.rs_stop(100);
    17  end;
    18  /
    Run1 draaide in 341 hsecs
    Run2 draaide in 348 hsecs
    Run1 draaide in 97,99% van de tijd
    Naam                                                    Run1      Run2  Verschil
    STAT.session cursor cache hits                             0       998       998
    STAT.opened cursors cumulative                             0     1,000     1,000
    STAT.parse count (total)                                   0     1,000     1,000
    LATCH.shared pool                                      1,047     3,043     1,996
    STAT.recursive calls                                   3,001     1,001    -2,000
    LATCH.library cache pin allocation                         8     2,011     2,003
    LATCH.library cache pin 2,048 6,044 3,996
    LATCH.library cache 2,056 6,060 4,004
    Run1 latches totaal versus run2 -- verschil en percentage
          Run1      Run2  Verschil     Pct
        48,522    60,548    12,026  80.14%
    PL/SQL-procedure is geslaagd.Regards,
    Rob.

  • DYNAMIC QUERY FOR INSERT USING SELECT

    Hi All,
    I am facing an issue...I am un bale to do an dynamic query. i have explained my code and the sample create, insert statements. I shud insert values in a table using a select statement dynamically..
    create table listing (tel_no varchar2(16), list_key varchar2(30));
    create table dummy_extract ( extract_name varchar2(10),extract_query varchar2(400),extract_date date );
    create table dummy_query (tel_no varchar2(16), list_key varchar2(30));
    insert into listing (tel_no ,header_key) values ('123456','123.23');
    insert into dummy_extract (extract_name,extract_query,extract_date) values ('SP','SELECT TEL_NO, LIST_KEY FROM LISTING','10-DEC-2010');
    SET SERVEROUTPUT ON
    declare
    CURSOR CUR_QUERY IS
    SELECT * FROM DUMMY_EXTRACT ;
    V_STMT VARCHAR2(4000);
    BEGIN
    FOR I IN CUR_QUERY LOOP
    V_STMT := 'INSERT INTO DUMMY_QUERY VALUES ' ||(I.EXTRACT_QUERY ) ;
    EXECUTE IMMEDIATE V_STMT using i.extract_query;
    DBMS_OUTPUT.PUT_LINE (V_STMT);
    END LOOP;
    END ;

    Hi Blue shadow and Saubik,
    I tried my query.It shows missing expression...Could you tell me the reason...
    SET SERVEROUTPUT ON
    declare
    CURSOR CUR_QUERY IS
    SELECT * FROM DUMMY_EXTRACT ;
    V_STMT VARCHAR2(4000);
    BEGIN
    FOR I IN CUR_QUERY LOOP
    --V_STMT := 'INSERT INTO'|| DUMMY_QUERY ||'VALUES ' ||(I.EXTRACT_QUERY ) ;
    EXECUTE IMMEDIATE 'INSERT INTO DUMMY_QUERY VALUES ' ||(I.EXTRACT_QUERY ) ;
    DBMS_OUTPUT.PUT_LINE (V_STMT);
    END LOOP;
    END ;
    Error report:
    ORA-00936: missing expression
    ORA-06512: at line 14
    00936. 00000 - "missing expression"
    *Cause:   
    *Action:                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Unable to retrieve results using dynamic query

    Hi Experts,
    I have created a custom table and have created a custom bol to integrate it with web ui. I have redefined the dynamic query result method of genil layer. I find the data into LT_RESULT but when I invoke the root list method the LR_OBJECT does not contain the values.
    Please see below the code that I have written.
    ====================================
    METHOD IF_GENIL_APPL_INTLAY~GET_DYNAMIC_QUERY_RESULT.
    DATA: LR_OBJECT TYPE REF TO IF_GENIL_CONT_ROOT_OBJECT,
    LT_RESULT TYPE TABLE OF ZCRMST_XXXX,
    LV_DYN_WHERE TYPE STRING,
    LV_LEN TYPE I,
    LS_RANGE TYPE SELOPTOBJ.
    DATA: LT_XXXX TYPE TABLE OF SELOPTOBJ,
    LT_YYYY TYPE TABLE OF SELOPTOBJ.
    FIELD-SYMBOLS: <LFS_RESULT> TYPE ZCRMST_XXXX,
    <LFS_SELECTION_RANGE> TYPE GENILT_SELECTION_PARAMETER.
    decomposition of selection parameters and build a dynamic where condition
    SELECT * FROM ZXXXX INTO TABLE LT_RESULT[].
    CHECK LINES( LT_RESULT[] ) > 0.
    LOOP AT LT_RESULT[] ASSIGNING <LFS_RESULT>.
    LR_OBJECT = IV_ROOT_LIST->ADD_OBJECT( IV_OBJECT_NAME = 'Root'
    IS_OBJECT_KEY = <LFS_RESULT>-XXXX ).
    CHECK LR_OBJECT IS BOUND.
    LR_OBJECT->SET_QUERY_ROOT( ABAP_TRUE ).
    ENDLOOP.
    ENDMETHOD.
    ==================================================
    Thanks in advance,

    Hi,
    Please check your get_objects method of the genil class. I made some changes to my implementation of get_objects method and it fixed the problem.
    Regards,
    Sandeep

  • Converting rows to columns using dynamic query.

    I am trying to use the below code that I founnd on the web to conver rows to columns. the reason that I want to use dynamic query is that the number of rows are not know and changes.
    declare
        lv_sql varchar2(32767) := null ;
    begin
        lv_sql := 'SELECT Iplineno ';
        for lv_rec in (SELECT distinct vendor from bidtabs  where letting = '10021200' and call ='021')
        loop
            lv_sql :=   lv_sql
                        || CHR(10)
                        || ', MAX( DECODE( vendor, '
                        || chr(39)
                        || lv_rec.vendor
                        || CHR(39)
                        || ', bidprice, NULL ) ) as "'
                        || lv_rec.vendor
                        || '" ' ;
        end loop;
        lv_sql :=   lv_sql
                    || CHR(10)
                    || 'FROM bidtabs  where letting =  ''10021200''  and call =  ''021''  and lineflag = ''L''  '
                    || CHR(10)
                    || 'GROUP BY iplineno ;' ;
    here is the result
    BIDPRICE     CALL     IPLINENO     LETTING     VENDOR
    9,585     021     0010     10021200     C0104        
    1,000     021     0020     10021200     C0104        
    1,000     021     0030     10021200     C0104        
    17     021     0040     10021200     C0104        
    5     021     0050     10021200     C0104        
    11,420     021     0010     10021200     K0054        
    1,100     021     0020     10021200     K0054        
    1,100     021     0030     10021200     K0054        
    5     021     0040     10021200     K0054        
    3     021     0050     10021200     K0054        
    8,010     021     0010     10021200     V070         
    900     021     0020     10021200     V070         
    1,320     021     0030     10021200     V070         
    11     021     0040     10021200     V070         
    3     021     0050     10021200     V070         
    and here is the desired output
    CALL     IPLINENO     LETTING      C0104              K0054              V070         
    021     0010     10021200      9,585                     11,420                                   8,010
    021     0020     10021200      1,000       1,100     900
    021     0030     10021200      1,000     1,100     1,320
    021     0040     10021200       17     5     11
    021     0050     10021200      5     3     3

    Here is the error message I am getting:
    RA-06550: line 22, column 43:
    PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
    begin case declare end exception exit for goto if loop mod
    null pragma raise return select update while with
    <an identifier> <a double-quoted delimited-identifier>
    <a bind variable> << close current delete fetch lock insert
    open rollback savepoint set sql execute commit forall merge
    pipe

  • Returning a result set/record from a dynamic query

    There seems to be plenty of examples for using Native Dynamic Sql to formulate and execute a dynamic query, however there are no examples of returning a result set or records which contain the rows of data that are retrieved by executing the query. Could someone give us an example?

    Welcome to the Oracle forum....
    CREATE OR REPLACE PACKAGE curspkg_join AS
    TYPE t_cursor IS REF CURSOR ;
    Procedure open_join_cursor1 (n_EMPNO IN NUMBER, io_cursor IN OUT t_cursor);
    END curspkg_join;
    Create the following Oracle package body on the Oracle server:
    CREATE OR REPLACE PACKAGE BODY curspkg_join AS
    Procedure open_join_cursor1 (n_EMPNO IN NUMBER, io_cursor IN OUT t_cursor)
    IS
    v_cursor t_cursor;
    BEGIN
    IF n_EMPNO <> 0
    THEN
    OPEN v_cursor FOR
    SELECT EMP.EMPNO, EMP.ENAME, DEPT.DEPTNO, DEPT.DNAME
    FROM EMP, DEPT
    WHERE EMP.DEPTNO = DEPT.DEPTNO
    AND EMP.EMPNO = n_EMPNO;
    ELSE
    OPEN v_cursor FOR
    SELECT EMP.EMPNO, EMP.ENAME, DEPT.DEPTNO, DEPT.DNAME
    FROM EMP, DEPT
    WHERE EMP.DEPTNO = DEPT.DEPTNO;
    END IF;
    io_cursor := v_cursor;
    END open_join_cursor1;
    END curspkg_join;
    Dim Oraclecon As New OracleConnection("Password=pwd;" & _
    "User ID=uid;Data Source=MyOracle;")
    Oraclecon.Open()
    Dim myCMD As New OracleCommand()
    myCMD.Connection = Oraclecon
    myCMD.CommandText = "curspkg_join.open_join_cursor1"
    myCMD.CommandType = CommandType.StoredProcedure
    myCMD.Parameters.Add(New OracleParameter("io_cursor", OracleType.Cursor)).Direction = ParameterDirection.Output
    myCMD.Parameters.Add("n_Empno", OracleType.Number, 4).Value = 123
    Dim myReader As OracleDataReader
    Try
    myCMD.ExecuteNonQuery()
    Catch myex As Exception
    MsgBox(myex.Message)
    End Try
    myReader = myCMD.Parameters("io_cursor").Value
    Dim x, count As Integer
    count = 0
    Do While myReader.Read()
    For x = 0 To myReader.FieldCount - 1
    Console.Write(myReader(x) & " ")
    Next
    Console.WriteLine()
    count += 1
    Loop
    MsgBox(count & " Rows Returned.")
    myReader.Close()
    Oraclecon.Close()
    The above code is working in one of our application; which is using ref cursor as result set and get from procedure. I hope you can found more code by google and/or search in this forum as well; if above code is not useful to you.
    HTH
    Girish Sharma

  • Sort problem on dynamic query !!

    Hi,
    I have a dynamic query written in pl/sql, when I check "Sort" for each field in Report Attribute, error message raised up as "ORA-01785: ORDER BY item must be the number of a SELECT-list expression".
    If I do not check Sort, it works fine. In my apps I need all fields sorted by user, how to fix this problem?
    My query as below:
    declare
    query varchar2(2000):='select';
    s_class varchar2(1000);
    cursor c1 is select * from demo_preference;
    begin
    for c1_val in c1 loop
    if c1_val.login is not null then
    query := query ||' ' || 'login' || ',';
    end if;
    if c1_val.id is not null then
    query := query ||' ' || 'id' || ',';
    end if;
    end loop;
    query := SUBSTR(query, 1, length(query)-1);
    s_class := '(NVL(:P2_class, ''%'' || ''null%'') = ''%'' || ''null%'' OR
    EXISTS (SELECT 1 FROM apex_collections WHERE collection_name = ''P2CLASSCOL'' AND c001 = class))';
    query := query ||' ' || 'from ming.reg_report_view1 where'
    || ' ' || s_class;
    return(query);
    end;

    Maybe the internally mapped column used when you clicked on sort is not shown in the report. Try using aliases when you construct the query string, it could help apex internally in identifying a column even if its order changes for a different user. After all the column order in the code is dynamic and I guess even the no of columns displayed might vary both of which could make sorting on a column identified with a number, invalid.
    How about displaying the report query somewhere, so that you know what is the exact query being processed, it might give you better information about the problem.
    If the problem persists, then use a collection that is fetched those record using the same query string and change the report to refer the collection and then set column sorting on. This way apex would get confused on what columns are being sorted and it would just sort on a c001..c050 column as though it was a string(yes problems with number columns sorting when you do this).

  • How to fetch indivdual rows from a dynamic query.

    Hi,
    I wish to fetch the individual rows returned from a dynamic query.
    if my dynamic query is:
    dyn_stmt := select col1, col2, col3
    from tab1;
    The query returns multiple rows.
    Then how to fetch individual rows of this query ?
    Please explain.

    declare
      cur_test sys_refcursor;
      c1 varchar2(30);
      c2 number;
      c3 date;
    begin
      dyn_stmt := select col1, col2, col3 from tab1;
      OPEN cur_test FOR dyn_stmt;
      LOOP
        FETCH cur_test INTO c1, c2, c3;
        IF cur_test%NOTFOUND THEN
          EXIT;
        END IF;
        -- Process this row
      END LOOP;
      CLOSE cur_test;
    END;

  • Dynamic query in ABAP

    Can we use dynamic query in ABAP?

    1. Dynamic where clause
    You can use an internal table to build a dynamic where clause:
    data: where_tab(30) occurs 1 with header line,                     
             where_clause(30) type c.                                     
    Build the where clause. Will look like this when finished
    WHERE ZAFSTMD02 = 'X' AND rbusa = '5145'
    With a constant, result: ZAFSTMD01 = 'X'
    concatenate 'ZAFSTMD' zcostcheck-zmaaned  ' = ''X'''  into where_clause.                              
    Append to internal table where_tab
    append where_clause to where_tab.                                  
    With a variable, result: AND rbusa = '5145'
    concatenate 'AND rbusa = '  ''''  i_tab-zgsber  ''''
    append where_clause to where_tab.                                  
    Select
    select * from zcostfreq                                           
         where (where_tab).                                              
    endselect.                                                        
    Note that you can combine static and dynamic where clauses:
    select * from zcostfreq                                           
         where bukrs = '2021' AND
                                  (where_tab).                                              
    endselect.                                                        
    2. Using a dynamic table name
    This report prints the number og entries in a table. The table name is
    specified by a parameter.
    data:
      l_count type i.
    parameters:
    p_tab type tabname.
    start-of-selection.
      select count(*) from (p_tab) into l_count.
      write: / 'Number of entries in table ', p_tab, l_count.
    3. Dynamic retrieval and writing of data
    In this example, data is retrieved from the table selected on the selection
    screen, and the contents of the
    table is written to the screen.
    DATA:
    Create variable that can contain referecene to any data
      dataref TYPE REF TO data.
    FIELD-SYMBOLS:
      <row>         TYPE ANY,
      <component>   TYPE ANY.
    PARAMETERS:
    p_tab TYPE tabname.
    START-OF-SELECTION.
    Create a workarea for the tabel selected on the selection screen
      CREATE DATA dataref TYPE (p_tab).
    The variable dataref cannot be accessed directly, so a field symbol is
    used
      ASSIGN dataref->* TO <row>.
      SELECT *
        FROM (p_tab) UP TO 10 ROWS
        INTO <row>.
        NEW-LINE.
        DO.
        Write all the fields in the record   
          ASSIGN COMPONENT sy-index
            OF STRUCTURE <row>
            TO <component>.
          IF sy-subrc <> 0.
            EXIT.
          ENDIF.
          WRITE <component>.
        ENDDO.
      ENDSELECT.
    4. Dynamic SELECT
    TYPES:
      BEGIN OF st_bseg,
        bukrs LIKE bseg-bukrs,
        belnr LIKE bseg-belnr,
        dmbtr LIKE bseg-dmbtr,
      END OF st_bseg.
    DATA:
      sel_list   TYPE STANDARD TABLE OF edpline,
      li_bseg    TYPE STANDARD TABLE OF st_bseg,
      l_bseg     TYPE st_bseg.
    START-OF-SELECTION.
      APPEND 'bukrs belnr dmbtr' TO sel_list.
      SELECT (sel_list)
        FROM bseg  UP TO 100 ROWS
        INTO TABLE li_bseg.
      LOOP AT li_bseg INTO l_bseg.
        WRITE : / l_bseg-bukrs, l_bseg-belnr, l_bseg-dmbtr.
      ENDLOOP.

  • Display results from dynamic query created and executed inside procedure

    Hi;
    I have created this code:
    CREATE OR REPLACE PROCEDURE RunDynamicQuery(Var1 IN VARCHAR2, Var2 IN VARCHAR2, VAR3 IN VARCHAR2) AS
    -- Do something
    -- That ends up with a variable holding a query.... (just an example)
    MainQuery :='select sysdate from dual';
    end RunDynamicQuery;
    How can I run this procedure and see the result on the dymanic query generated inside it?
    BEGIN
    compare_tables_content('VAR1','VAR2','VAR3');
    END;
    Expected Output for this given example:
    20-05-2009 11:04:44 ( the result of the dymanic query inside the procedure variable MainQuery :='select sysdate from dual';)
    I tested with 'execute immediate':
    CREATE OR REPLACE PROCEDURE RunDynamicQuery(Var1 IN VARCHAR2, Var2 IN VARCHAR2, filter IN VARCHAR2) AS
    -- Do something
    -- That ends up with a variable holding a query.... (just an example)
    MainQuery :='select sysdate from dual';
    execute immediate (MainQuery );
    end RunDynamicQuery;
    BEGIN
    compare_tables_content('VAR1','VAR2','VAR3');
    END;
    Output:"Statement processed'' (no sysdate displayed ! )
    Please consider that the collums in the query are always dynamic... PIPELINE Table would not work because I would need to define a container, example:
    CREATE OR REPLACE TYPE emp_tabtype AS TABLE OF emp_type;
    FUNCTION RunDynamicQuery (p_cursor IN sys_refcursor)
    RETURN emp_tabtype PIPELINED
    IS
    emp_in emp%ROWTYPE;
    BEGIN
    LOOP
    FETCH p_cursor
    INTO emp_in;
    EXIT WHEN p_cursor%NOTFOUND;
    PIPE ROW (...)

    That would be a nice solution, thanks :)
    ''For now'' I implemented like this:
    My dynamic query now returns a single string ( select col1 || col2 || col3 from bla)
    This way I don't have dynamic collumns issue, and from business side, this ''string'' format works for them.
    This way I can use the pipelines to get the result out...
    OPEN myCursor FOR MainQuery;
    FETCH myCursor
    INTO myRow;
    WHILE (NOT myCursor%notFound) LOOP
    PIPE ROW(myRow);
    FETCH myCursor
    INTO myRow;
    END LOOP;
    CLOSE myCursor;

Maybe you are looking for

  • Credit Check

    Dear All, I have a requirement in credit management, A sales order should block either customer credit limit of Rs.1,00,000 is exceeds or any open item exists more than 30days. I am trying this using automatic credit control with the options of stati

  • HT204053 How can i use 2 apple ids on an ipad that i share with my wife?

    My wife uses her apple id on her iphone4, use my apple id in my iphone5.  I'd like to see both and have the seemless cloud sync with both apple ids on our shared ipad and pc without merging the data into a single id. Any help would be appreciated.

  • Dreamweaver MX 2004 hangs (10.5.8 PowerMac G5)

    After not using Dreamweaver MX 2004 (7.0) since Mar 17, 2011, I tried to launch it today.  The icon bounced once, the beach ball whizzed and and application hangs. I deleted dreamweaver prefs: hang Checked for and installed Dreamweaver update to 7.0.

  • Tables linking the invoice and accounting document

    Hi, Can anyone tell me tables linking the invoice and accounting details table BSEG? Regards, Shanu

  • Printing Quarter fold envelopes.

    I have a Photosmart C8180 All in One printer and it doesn't  have a quarter fold print option listed in the ppaper sizes. Is there a way to adust the printer to do this? Ed M