Dinamic Query Rowtype

Hi:
Anybody know how get Rowtype from one dinamyc Query like this
lc_SQL := 'SELECT';
For i in 1 ... N LOOP
lc_SQL := lc_SQL || Fieldi;
END LOOP;
OPEN Cursor FOR lc_SQL;
FETCH Cursor BULK COLLECT INTO xxxxxx
How I can know rowtype from Cursor to asign into xxxxxx

You can't get this information dynamically.
Dynamic SQL is mainly useful for varying the WHERE clause. As it happens we can also vary the names of the columns and even the tables we select from. But we cannot vary the signature of the query. The datatype structure and name(s) of the receiving variable (array, record, whatever) have to be fixed. Otherwise nothing will compile.
The workaround is to use DBMS_SQL which does support some metadata functionality. However, the only way to make the receiving variable dynamic is code your entire program in a dynamic fashion. Which way madness lies.
The other approach is to use objects. You could frame your dynamic select statements as casts to object types and select into an array of ANYTYPE. Of course, you would have to declare your TYPEs in DDL beforehand so it's not very dynamic. In fact, forget about it.
Essentially, PL/SQL is a strongly typed, non-reflective language. Deal with it. If you want weak (i.e. runtime) type casting (and the concomitant performance hit) use Python.
Cheers, APC

Similar Messages

  • Dinamic Query SQL injection

    I would like to do a dinamic query. I dont know the number of columns of the column and the table, and things like that. I�m worried about sql injection how can i avoid it.
    For example,
    select column1,column2,....
    from tabla
    where column1=columna2 and...
    I know the format i must build it with Java.

    PreparedStatement can avoid most of the standard SQL injection attacks. However, you should not allow a client to request arbitrary SQL statements to be executed unless you have some serious security in your network and are behind a very good firewall.
    - Saish

  • Dinamic query on 8.0.5 db

    Hi.
    I4m traying to make a dinamic query as:
    "select ec_ctnt.filename
    from ec_ctnt, ec_prditm_ctntlst
    where ec_ctnt.ctntid = ec_prditm_ctntlst.ctntid and ec_prditm_ctntlst.prditmid = ?" using thin jdbc driver, but compiling it with JDeveloper obtain the error messaege "ORA-01008: Not all variables bound", but I include the CalledStatement.setInt() method after this line.

    It appears you are using a PreparedStatement object for your query, in which case you need to use the prepared statement object's setInt(int parameterIndex, int x) method.
    For example:
    PreparedStatement pstmt = conn.prepareStatement("... = ?");
    pstmt.setInt(1, <somenumber>);
    null

  • Dinamic query

    Hello!
    For first, sorry for my ignorance, but I'm not DBA and who is DBA at my company couldn't help me (I don't know why!).
    I have a problem with dinamic filters in some queries.
    I want to select N rows of a table, but the query can vary in a series of filters, it depending on the parameters.
    For example:
    first case:
    SELECT X FROM TABLE
    WHERE X = 'TEST';
    second case:
    SELECT X FROM TABLE
    WHERE X = 'TEST'
    OR X = 'AAA';
    Did you understand? This is the problem. How can I concatenate this clause "OR" in the end of the query when I want, without create it as a string and using "EXECUTE SQL"...?
    I want to use it as a dinamic command...
    One more time, sorry if this is a question that only fools do. I'm learning by myself, and at the moment I'm lost. =)
    Thanks!

    in this case performance problem occurs for the NULL case only?
    create table tab (x varchar2(16));
    insert into tab values ('TEST');
    insert into tab values ( NULL );
    begin
       for i in 1..1000000 loop
           insert into tab values ( to_char(i) );
       end loop;
    end;
    create unique index ui_tab_x on tab(x) nologging;
    exec dbms_stats.gather_table_stats(user, 'tab');
    commit;
    set timing on
    set autotrace traceonly
    SELECT X FROM tab WHERE X = 'TEST' or X = DECODE(1,NULL,X,1) ;
    Elapsed: 00:00:00.00
    Execution Plan
    Plan hash value: 3421616299
    | Id  | Operation          | Name     | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT   |          |     2 |    12 |     4   (0)| 00:00:01 |
    |   1 |  CONCATENATION     |          |       |       |            |          |
    |* 2 | INDEX UNIQUE SCAN| UI_TAB_X | 1 | 6 | 2 (0)| 00:00:01 |
    |* 3 | INDEX UNIQUE SCAN| UI_TAB_X | 1 | 6 | 2 (0)| 00:00:01 |
    Predicate Information (identified by operation id):
    2 - access("X"='TEST')
    3 - access("X"='1')
    Statistics
              1  recursive calls
              0  db block gets
    6 consistent gets
              0  physical reads
              0  redo size
            444  bytes sent via SQL*Net to client
            384  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
              2  rows processed
    SELECT X FROM tab WHERE X = 'TEST' or X = DECODE(NULL,NULL,X,NULL) ;
    1000001 rows selected.
    Elapsed: 00:00:05.87
    Execution Plan
    Plan hash value: 1995730731
    | Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |      |     1 |     6 |   503   (9)| 00:00:07 |
    |* 1 | TABLE ACCESS FULL| TAB | 1 | 6 | 503 (9)| 00:00:07 |
    Predicate Information (identified by operation id):
    1 - filter("X"="X" OR "X"='TEST')
    Statistics
              1  recursive calls
              0  db block gets
    68353 consistent gets
              0  physical reads
              0  redo size
       16555973  bytes sent via SQL*Net to client
         733710  bytes received via SQL*Net from client
          66668  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
        1000001  rows processedwhat is your Oracle version? I did above test on 10gR2. And are you using bind variables for this operation?
    if you are using bind variables force the NOT NULL cases to be parsed differently than NULL case, so guarantee for different execution plans no matter which comes first.
    one way to do this can be with an if block and use comments in your code.
    if arg is NOT NULL then
       select /* NOT null case */ X FROM tab WHERE X = 'TEST' or X = DECODE(arg,NULL,X,arg) ;
    else
       select /* null case */ X FROM tab WHERE X = 'TEST' or X = DECODE(arg,NULL,X,arg) ;
    end if;  

  • How to dump a query on a XLS file?

    I´m working in a stored procedure on that i can send a dinamic query and it return me the result into a xls file.
    I´ve found the way to generate that xls file from Pl/sql, but now I need be able to assing each field of each row into his corresponding cell. For this I need to put each field of each row in a variable and then work on it.
    For generate xls file, I´ve created a datatype by following the indications of Jasson Bennet´s blog.
    http://radio-weblogs.com/0137094/2006/10/26.html
    In the example, values are assigned directly to the cells. But it not is valid for me because I dont know what will be these...
    I think that if you want see the blog, you´ll can understand better what I´m refering...
    Thanks for your time...

    Strange requirement, you don't know the query, the columns and the number of rows you get, but you know that you want the value of the second column of the second row :)
    But try this
    declare
      t_c integer;
      t_r integer;
      t_v varchar2(100);
    begin
      t_c := dbms_sql.open_cursor;
      dbms_sql.parse( t_c, q''select 'Roy' name, 'sales' deptno, 25 age from dual
    union all select 'Sara', 'HHRR', 30 from dual
    union all select 'Mike', 'finances', 35 from dual'', dbms_sql.native );
      dbms_sql.define_column( t_c, 2, t_v, 100 );
      t_r := dbms_sql.execute( t_c );
      t_r := dbms_sql.fetch_rows( t_c );
      t_r := dbms_sql.fetch_rows( t_c );
      dbms_sql.column_value( t_c, 2, t_v );
      dbms_sql.close_cursor( t_c );
      dbms_output.put_line( t_v );
    end;
    /

  • How to make a search in a form

    Hi
    I have a form with a lot of items(name date,age,height) that i can use to make a search . I found many problems for the search , infact i had to create many cursors, one for each case. For example i would search for age and height or just from date and so on.
    How can i make it more easy?
    Can i use a dinamically query for a cursor ?
    PLZ HELP

    if you don't use oracle default search buttons, then you may code your own search buttons, inside, you may ,
    e.g., user might want to enter height and age fields(Assume the table columns are HEIGHT and AGE),
    then use,
    IF :heightitem is not null then
    w_str := ' AND HEIGHT ='||:heightitem;
    END IF;
    IF :AGEITEM IS NOT NULL THEN
    w_str := w_str||' AND AGE='||:ageitem;
    END IF;
    then you set_block_property('..',default_where,w_str); then execute_query. In order to avoid giving user blank form fields when no records found, which oracle did this badly, then you may use SELECT COUNT(*) into cnt FROM ... WHERE ...w_str to detect the cnt, if cnt > 0 then execute_query, if not, then shoot no record data found message out.

  • Db 이전 문제때문에 질문올립니다.

    source db : Oracle 9i ( LANG KO16KSC5601 )
    target db: Oracle 9i ( LANG UTF - 8 )
    source db 에서 target db 로 데이터 이전 준비중입니다.
    아래와 같은 방법으로 현재 99% 성공인데 몇가지 걸리는게 있습니다.
    1. source db user 당 export
    2. export file 에서 create 문만 추출
    3. target db 에서 create 문 실행
    4. pl/sql 로 target db 의 char, varchar size 를 1.5 로 증가( varchar2 는 당연히 4000까지만 )
    5. export 받은 dump 파일 ignore = y 로 target db 에 import
    ko16 에서 utf-8 로 이전하는 과정에서 한글이 2byte -> 3byte 로 커지는 문제때문에 위와 같은 방법을 사용했는데요
    문제는 기존에 varchar2(4000) 으로 사용하던 필드입니다.
    이미 3000 byte 이상 입력되어 있는 상태이기때문에
    테이블 생성시에 varchar2(4000) => clob 으로 변경후에
    위 방법을 import 시에
    ORA-01461: can bind a LONG value only for insert into a LONG column
    에러가 발생합니다.
    metalink 에서 뒤져보니 clob 자체가 insert 문이 다르더군요.
    그래서.. 생각한것이 db link 을 이용해서 한줄씩 이동할려고 했으나
    declare
         lob_loc CLOB;
         cursor emp is
                   select
                   content
                   from 테이블명@디비링크;
         atc TBL_MP_MEMO%ROWTYPE;          
    begin
    -- 커서 루프돌면서 local db 에 clob insert
    end;
    ORA-1406 에러가 발생하네요. (인출된 열이 짤렸습니다)
    역시 metalink 을 뒤척여봤으나 뽀족한 방법은 없는것 같습니다.
    정 안되면 java 로 프로그램을 짜셔 한줄씩 입력하려고 하고 있는데
    그냥 pl/sql 또는 오라클 자체기능으로는 불가능할까요?
    고수님들의 가르침을 기다리겠습니다.

    저도 이것때문에 한참 고민을 했는데..
    먼저... 한가지 말씀드리면..metalink에서 UTF8로 변경하지 말고
    AL32UTF8을 사용하라더군요.. UTF8은 너무 옛날에
    쓰던 것이라서 모가 지원 안된다던거 같던데..;;
    이미 하셨으니 어쩔 수 없죠..
    아래는 제가 long type의 데이터를 옮길 때에 사용했던 겁니다.
    문제는 그 때에도 데이터가 짤렸는데.. 수치값을 늘려주면 될 것 같기도 합니다.
    예>
    - test_contents 라는 테이블을 생성하고
    dl_smsvr1이라는 db링크에서 long typpe이 있는
    데이터를 가져오고자 한다.
    참고로 long type은 varchar2(32767)으로 pl/sql에서 정의한다.
    varchar2는 32767이 최대값이다.
    -- 주의사항
    위 pl/sql이 수행되면 auto commit이 되고 만다. 즉 rollback이 안되니 주의할것.
    원본 데이터를 옮겨두고 또는 exp백업을 하고 나서 수행하자.
    create table test_contents
    ( res_idx number(10),SRC_TYPE char(1),CONTENT long) tablespace mail2;
    DECLARE
    RES_IDX NUMBER(10);
    SRC_TYPE CHAR(1);
    CONTENT VARCHAR2(32767);
    cursor query is
    SELECT *
    FROM MAIL2.IM_CONTENT@dl_smsvr1;
    thisrow query%rowtype;
    begin
    open query;
    fetch query into thisrow;
    RES_IDX := thisrow.res_idx;
    SRC_TYPE := thisrow.src_type;
    CONTENT := thisrow.content;
    loop
    fetch query into thisrow;
    exit when query%notfound;
    INSERT INTO test_contents VALUES(thisrow.RES_IDX, thisrow.SRC_TYPE, thisrow.CONTENT);
    end loop;
    end;
    /

  • Query data dinamically

    I want to execute a query that it is formed dinamically based in some text items that I have in the form; I want to use the Execute Query button on the default toolbar. My question is how to pass the text item content as a parameter to the where clause in datablock property field?
    Thanks

    Hello
    you can use the SET_BLOCK_PROPERTY procedure for both the where clause or an order by.
        v_WHERE := F_SET_WHERE;     -- construct your where clause in a function
        GO_BLOCK ( <my_block> );
        CLEAR_BLOCK ( NO_VALIDATE );
        SET_BLOCK_PROPERTY ( <my_block>, DEFAULT_WHERE, v_WHERE );
        EXECUTE_QUERY;Bernd

  • IS IT POSSIBLE TO CHANGE DINAMICALLY THE SOURCE OF A QUERY?

    IS IT POSSIBLE TO CHANGE DINAMICALLY THE SOURCE OF A QUERY, AND TO SHOW DATA FROM DIFERENT TABLES, BASED IN USER PARAMETER VALUE?.
    EXAMPLE:
    IF USER PARAMETER = 1 THEN
    SELECT COLUMN1 FROM TABLE1
    ELSIF USER PARAMETER = 0 THEN
    SELECT COLUMN2 FROM TABLE2
    END IF;
    ANY OTHER IDEA??
    THANKS FOR HELPS.

    Read the online help about lexical parameters.
    Select a from &p_1
    should work.

  • ROWTYPE to get better query ?

    Hello,
    I have two identical tables:
    PHOTOS_TEMP AND IMAGES_TEST
    (ID PK number ,
    content blob,
    filename varchar2 (200),
    mimetype varchar2 (200),
    filesize varchar2 (200),
    res_id FK number,
    watermarked varchar2 (1))I have CODE 1, I want to make it more effecient perhaps by using %ROWTYPE,
    So, I tried CODE 2, but it did not work. It tells, "Too many values .... CONTENT must be declared ...."
    Can you plesae tune Code 1 ??
    h1. CODE 1 is working fine
    DECLARE
    type source_col is table of blob index by pls_integer ;
    V_source source_col;
    type id_col is table of number index by pls_integer ;
    V_id id_col;
    type char_col is table of IMAGES_TEST.FILENAME%TYPE index by pls_integer ;
    V_filename char_col;
    V_mimetype char_col;
    begin
    select content,filename,mimetype,id bulk collect into
    V_source,v_filename,v_mimetype,v_id from photos_temp
    where  temp = :P700_TEMP_IMAGE   for update  ;
    for i in V_source.first .. V_source.last
    loop
    ORDSYS.ORDImage.process(V_source(i), 'fixedScale=800 500');
    end loop;
    forall i in V_source.first .. V_source.last
    insert into IMAGES_test
    (res_id ,CONTENT,filename,mimetype,filesize,watermarked)
    values
    (:P700_res_ID ,V_source(i),V_filename(i),V_mimetype(i),
    dbms_lob.getlength(V_source(i)), 'Y');
    COMMIT;
    EXCEPTION
       WHEN OTHERS THEN
       RAISE;
    END;h1. CODE 2 supposed to be more efficient, but not working ?
    DECLARE
    type new_row is table of IMAGES_TEST%rowtype index by pls_integer ;
    v_row new_row;
    begin
    -- This may collect more than one row
    select * bulk collect into
    v_row from photos_temp
    where  temp = :P700_TEMP_IMAGE   for update  ;
    for i in v_row.id.first .. v_row.id.last
    loop
    ORDSYS.ORDImage.process(v_row.content(i), 'fixedScale=800 500');
    end loop;
    forall i in v_row.id.first .. v_row.id.last
    insert into IMAGES_test
    (res_id ,CONTENT,filename,mimetype,filesize,watermarked)
    values
    (:P700_res_ID ,v_row.contnet(i),v_row.filename(i),v_row.mimetype(i),
    dbms_lob.getlength(v_row.content(i)), 'Y');
    COMMIT;
    EXCEPTION
       WHEN OTHERS THEN
       RAISE;
    END;Best Regards,
    Fateh
    Edited by: Fateh on Nov 26, 2012 5:22 AM

    hi,
    In your CODE 1
    select content,filename,mimetype,id bulk collect into
    V_source,v_filename,v_mimetype,v_id from photos_temp
    where  temp = :P700_TEMP_IMAGE   for update  ;
    -- temp is not a collumn name nor a variable name
    ...So I think that does not work.
    In code 2 you must use the index "( i)" on the table variable and not on the attribute. So:
    v_row.contnet(i) --THIS IS WRONG!
    v_row(i).contnet -- This is OK
    Also:
    v_row.id.first --THIS IS WRONG!
    v_row.first --This is OK
    Below is an working example:
    insert into photos_temp (id ,filename) values ( 1,'peter');
    insert into photos_temp (id ,filename) values ( 2,'Fateh');
    commit;
    DECLARE
    type new_row is table of IMAGES_TEST%rowtype index by pls_integer ;
    v_row new_row;
    begin
      select * bulk collect into
       v_row from photos_temp
      --where  temp = :P700_TEMP_IMAGE  
      for update  ;
      --for i in v_row.id.first .. v_row.id.last
      for i in v_row.first .. v_row.last
      loop
      DBMS_OUTPUT.PUT_LINE('Id: ' || v_row(i).id || ' filename: ' || v_row(i).filename);
      end loop;
    end;
    Result:
    Id: 1 filename: peter
    Id: 2 filename: FatehAnd in your case for code 2 simplyfied:
    DECLARE
    type new_row is table of IMAGES_TEST%rowtype index by pls_integer ;
    v_row new_row;
    begin
      select * bulk collect into
       v_row from photos_temp
      --where  temp = :P700_TEMP_IMAGE  
      for update  ;
      --forall i in v_row.id.first .. v_row.id.last
      forall i in v_row.first .. v_row.last
      insert into IMAGES_test
      (id ,filename)
      values
      (v_row(i).id, v_row(i).filename);
    end;
    select
      id
      ,filename
    from
      images_test;
    Result:
    ID FILENAME                                                                                                                                                                                              
    1 peter                                                                                                                                                                                                   
    2 Fateh                                                                                                                                                                                                    Whoever this works in:
    Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
    PL/SQL Release 11.2.0.1.0 - Production
    "CORE     11.2.0.1.0     Production"
    TNS for 64-bit Windows: Version 11.2.0.1.0 - Production
    NLSRTL Version 11.2.0.1.0 - Production
    I think in oracle 9 you must use seperate table variables and not one table variable of a scalar type.
    Regards,
    Peter

  • Error while querying plsql table.

    create table emp(eno number, ename varchar2(20), sal number(10,2), dno number);
    create table dept(dno number, dname varchar2(10));
    DECLARE
    TYPE EmpTabTyp1 IS TABLE OF emp%ROWTYPE INDEX BY BINARY_INTEGER;
    emp_tab1 EmpTabTyp1;
    l_str_name varchar2(20);
    begin
    select eno, ename, sal bulk collect into emp_tab1 from emp;
    select et1.ename into l_str_name from dept dp , TABLE(CAST(emp_tab1 EmpTabTyp1)) et1 WHERE dp.dno = et1.dno
    end;
    Getting below error:
    ERROR at line 8:
    ORA-06550: line 7, column 131:
    PL/SQL: ORA-00933: SQL command not properly ended
    ORA-06550: line 7, column 3:
    PL/SQL: SQL Statement ignored
    ORA-06550: line 8, column 4:
    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 de
    Thanks,
    Vinodh

    ora_1978 wrote:
    create table emp(eno number, ename varchar2(20), sal number(10,2), dno number);
    create table dept(dno number, dname varchar2(10));
    DECLARE
    TYPE EmpTabTyp1 IS TABLE OF emp%ROWTYPE INDEX BY BINARY_INTEGER;
    emp_tab1 EmpTabTyp1;
    l_str_name varchar2(20);
    begin
    select eno, ename, sal bulk collect into emp_tab1 from emp;
    select et1.ename into l_str_name from dept dp , TABLE(CAST(emp_tab1 EmpTabTyp1)) et1 WHERE dp.dno = et1.dno
    end;
    Getting below error:
    ERROR at line 8:
    ORA-06550: line 7, column 131:
    PL/SQL: ORA-00933: SQL command not properly ended
    ORA-06550: line 7, column 3:
    PL/SQL: SQL Statement ignored
    ORA-06550: line 8, column 4:
    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 deThanks,
    VinodhYou cant query a PL/SQL table. You can query only a collection database object that is created and stored in the database.
    A simple reason is that PL/SQL code is processed by different engine and SQL code is processed by different engine. And your PL/SQL table is local to the PL/SQL code and is not available for the SQL engine.
    Edited by: Karthick_Arp on Apr 19, 2012 6:14 AM

  • How to input several queries at once in a text field, query from it?

    Hi ,
    I am starting out in oracle development and am currently attempting to develop a tool which uses a text item which can be updated by cut and paste (~ie from a spreadsheet) and then can query several tables(each as blocks joined by relations with the primary key of the first block being that of each item in the text feild) pulling back one row for each item entered in the original text item and displaying all the results as usual in the joined data fields. The problem i am having is attempting to 1. inserting multiple data items into the query box (text item), as the focus stays in the first item and i want to insert say 20 for the query by cut and paste. Secondly when populated i want to be able to use all these items to query the database when i press a button , however it shall only query the first row in the text item . Is it possible to loop in a when button pressed trigger? If not then i thought about inserting the rows in the original text item into a database table then joining it to the other tables by relation for query, however how do i loop through the text time and insert into a table( in a trigger or in a called procedure? any help would be much appreciated.

    Hi
    I am not sure if I understood completely what you want to do,
    but if you want to query a block using a list of values,
    you can modify dinamically the block where clause and use
    the operator "in".
    For example, loop through the values in the text item and
    build a list of values - at the end you'll get in a varchar2
    variable the following:
    '10, 12, 17, 22'
    Let's say the variable is called vList. Then you can use:
    set_block_property('myblock', default_where, 'thecolumn in ('||vList||')');
    So the block will retrieve all and only the records in the list.
    By the way, I suggest you break such long posts with blank lines
    between the paragraphs, it's easier to read!

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

  • How to treat data in a long query

    I have a query (over a table connected by dblink) that returns me a lot of rows (over 7 millions), when I try to got data at each row i got an out of memory problem. So I want to view records in legs, but i don't know how to do that in my procedure.
    The query is asigned to a cursor and I pass the data I need of each row to another table.
    This is the code I have:
    CURSOR r_cursor
    IS
    SELECT *
    FROM med_principio_activo@midblink
    cursor1 r_cursor%ROWTYPE;
    begin
    LOOP
    FETCH r_cursor
    INTO cursor1;
    EXIT WHEN r_cursor%NOTFOUND;
    SELECT MAX(SID)
    INTO medic
    FROM medicam
    WHERE cursor1.codmedic LIKE xkey;
    SELECT MAX(SID)
    INTO ppioact
    FROM activeingredient
    WHERE cursor1.codppioact LIKE xkey;
    INSERT INTO med_medicamentai
    (medicament, activeingredient
    VALUES (medic, ppioact
    COMMIT;
    END LOOP;
    I want to do legs of 10000 records to read all info and got memory free, but i don't know how to do that...
    Thnaks,

    Hi,
    instead of using PL/SQL using cursor you could have insert directly in the table,
    like
    INSERT INTO med_medicamentai
    (medicament, activeingredient
    VALUES (
    Before that we need to know how the data in med_principio_activo@midblink
    ,medicam and activeingredient are related.
    If you want to use cursor, then bulk collect will improve the performance.
    Please look at this link for more info.
    http://download.oracle.com/docs/cd/B14117_01/appdev.101/b10807/12_tune.htm#i49139
    Thanks

  • Assigning a query dynamically to a cursor based on IF ELSE condotion

    hello guys,
    we are facing a problem while creating a procedure.
    The procedure has been recreated in ORACLE from SQL SERVER 2005.
    the problem is that in SQL server we can assign a query dynamically to a cursor so that it will be called at execution time.But this is not the case in oracle, i.e in Oracle its not allowed to assign a query to a cursor dynamically(OR IS IT...!!!)
    the code is
    vr_SQL varchar2(400);
    declare
       cursor ord_cur  ;  <-----cursor declaration
      begin
       If v_pIsScrutiny = 0 then   +<--------------second condition+
          vr_SQL:='Select NVL(ServiceID,0)  ServiceID,OrdQty,+<-------query assignment to a variable+
              NVL(DrugID,0) DrugID,NVL(ServiceAmount,0) Rate,OrdDtlID 
              from Orderdtl inner join ordermst on Orderdtl.OrdID = ordermst.OrdID 
              Where Orderdtl.OrdID in (Select OrdID From Ordermst Where OrdVisitID = vr_visitid  
              and TO_CHAR(ordermst.OrdDate,''DD-MON-YYYY'') 
              Between TO_CHAR(vr_pActivationDate,''DD-MON-YYYY'') 
              and TO_CHAR(vr_pExpiryDate,''DD-MON-YYYY'') 
              ) And NVL(Orderdtl.Cancelled,0) = 0 And NVL(Orderdtl.PackageID,0) = 0 
              and NVL(Orderdtl.DrugID,0) = 0;';
        Else  +<--------------first condition+
            Update OrderDtl Set PackageID = 0 , AllocationID = 0 , ConsumptionID = 0 
            Where OrdID in (Select OrdID From Ordermst Where OrdVisitID = vr_visitid)  
            And AllocationID = v_pHCPAllocationID; 
           vr_SQL:= 'Select NVL(ServiceID,0)  ServiceID, +<-------query assignment to a variable+
           OrdQty,NVL(DrugID,0)  DrugID,NVL(ServiceAmount,0)
            Rate,OrdDtlID 
           from Orderdtl inner join ordermst on Orderdtl.OrdID = ordermst.OrdID 
           Where Orderdtl.OrdID in (Select OrdID From Ordermst Where OrdVisitID = vr_visitid  
           and TO_CHAR(ordermst.OrdDate,''DD-MON-YYYY'') 
           Between TO_CHAR(vr_pActivationDate,''DD-MON-YYYY'') 
           and TO_CHAR(vr_pExpiryDate,''DD-MON-YYYY'') 
           ) And NVL(Orderdtl.Cancelled,0) = 0 And NVL(Orderdtl.PackageID,0) = 0;'; 
        end if;
           ord_cur is vr_SQL; +<----------query assigned to a cursor variable+
        ord_rec ord_cur%ROWTYPE;
       if not ord_cur%ISOPEN then
            open ord_cur;
       end if;
        loop
        fetch ord_cur into ord_rec;
        exit when ord_cur%NOTFOUND;So currently we are stuck with this problem.
    Any solution would be of great help..
    thank you

    841363 wrote:
    hello guys,
    we are facing a problem while creating a procedure.
    The procedure has been recreated in ORACLE from SQL SERVER 2005.
    the problem is that in SQL server we can assign a query dynamically to a cursor so that it will be called at execution time.But this is not the case in oracle, i.e in Oracle its not allowed to assign a query to a cursor dynamically(OR IS IT...!!!)The problem is that you are thinking in SQL Server terms and Oracle just isn't SQL Server.
    You need to consider using ref cursors for such things (sys_refcursor) e.g.
    SQL> CREATE OR REPLACE PACKAGE reftest IS
      2    PROCEDURE test(P_no in number, cur_o OUT sys_refcursor);
      3  end;
      4  /
    Package created.
    SQL>
    SQL> CREATE OR REPLACE PACKAGE body reftest as
      2    PROCEDURE test(P_no in number, cur_o OUT sys_refcursor) as
      3      myexc exception;
      4    BEGIN
      5      if P_no = 1 then
      6        open cur_o for select empno, ename from emp;
      7      elsif p_no =2 then
      8        open cur_o for select deptno, dname from dept;
      9      else
    10        RAISE myexc;
    11      END IF;
    12    exception
    13      when myexc then
    14        raise_application_error(20991,'input must be 1 or 2');
    15    end ;
    16  end reftest;
    17  /
    Package body created.
    SQL> var x refcursor;
    SQL> exec reftest.test(1,:x);
    PL/SQL procedure successfully completed.
    SQL> print x;
         EMPNO ENAME
          7369 SMITH
          7499 ALLEN
          7521 WARD
          7566 JONES
          7654 MARTIN
          7698 BLAKE
          7782 CLARK
          7788 SCOTT
          7839 KING
          7844 TURNER
          7876 ADAMS
          7900 JAMES
          7902 FORD
          7934 MILLER
    14 rows selected.
    SQL> exec reftest.test(2,:x);
    PL/SQL procedure successfully completed.
    SQL> print x;
        DEPTNO DNAME
            10 ACCOUNTING
            20 RESEARCH
            30 SALES
            40 OPERATIONS
    SQL>

Maybe you are looking for

  • Why can you not leave a video message with Facetime?

    Would love to be able to leave a video message for the person I'm calling on Facetime if they can't answer.  Is this possible?

  • Officejet Pro L7590

    Help!  I have just replaced the Black/Yellow printhead, and now my printer wants to keep aligning and printing test page after every job!  How do I stop it?  I looked on the tools page and the self diagnostic box is highlighted and I cannot turn it o

  • Creation of ztable

    Hi, I am creating ztable with field                  zemail  data element as 'URL'  getting error as Table ZTABLE: Key length > 120 (Restricted functionality) Message no. DT214 Diagnosis The key length, i.e. the sum of the field lengths of all the ke

  • CD/DVD drive won't read any CDs or DVDs

    Whenever I insert a DVD, CD, or CD-ROM my computer won't read the disc. The computer starts making noise like it is reading the disc but then it stops. It tries 3 times (starts and stops) and then just spits the disc out. I can't watch movies, instal

  • Help! Starting Weblogic in Debug Mode

    Hi there Any clues/suggestions are greatly appreciated. Has anyone experienced any difficulties when starting weblogic in debug mode. More specifically, it cannot start correctly because it thinks that another instance is using the same port (definat