Using dynamic query to create sequence

Hello,
I created the sequence dynamically in a Procedure, but when I executed, it gave me an Insufficient privileges error:
SQL> create table dummy (id number, module_id varchar2(20), p_order number, status varchar2(1));
SQL> insert into dummy values (10, 'test', 0, 'D');
SQL> CREATE OR REPLACE PROCEDURE PRO_SEQ_ARRNGE(P_ID NUMBER) AS
V_MOD DUMMY.MODULE_ID%TYPE;
v_query1 varchar2(200);
v_query2 varchar2(200);
V_COUNT NUMBER;
begin
v_query1 := 'drop sequence unqid';
v_query2 := 'create sequence unqid start with 1 increment by 1 minvalue 1';
SELECT COUNT(*)
INTO V_COUNT
FROM USER_SEQUENCES
WHERE SEQUENCE_NAME = 'UNQID';
IF V_COUNT = 0 THEN
execute immediate v_query2;
ELSE
execute immediate v_query1;
execute immediate v_query2;
END IF;
SELECT distinct MODULE_ID INTO V_MOD FROM DUMMY WHERE ID = P_ID;
update dummy
set P_order = 0, status = 'D'
WHERE ID = P_ID
and module_id = v_mod;
--COMMIT;
execute immediate 'UPDATE DUMMY SET P_ORDER = UNQID.NEXTVAL WHERE MODULE_ID = V_MOD AND STATUS = ''A''';
--COMMIT;
END PRO_SEQ_ARRNGE;
SQL> exec PRO_SEQ_ARRNGE(10);
BEGIN PRO_SEQ_ARRNGE(10); END;
ERROR at line 1:
ORA-01031: insufficient privileges
ORA-06512: at "SYSTEM.PRO_SEQ_ARRNGE", line 15
ORA-06512: at line 1
Can you please advise how to resolve it?
Thanks in advance,
Tinku

When I try it, I get a different error
SQL> create table dummy (id number, module_id varchar2(20), p_order number, status varchar2(1));
Table created.
SQL>  insert into dummy values (10, 'test', 0, 'D');
1 row created.
SQL>  CREATE OR REPLACE PROCEDURE PRO_SEQ_ARRNGE(P_ID NUMBER) AS
  2  V_MOD DUMMY.MODULE_ID%TYPE;
  3  v_query1 varchar2(200);
  4  v_query2 varchar2(200);
  5  V_COUNT NUMBER;
  6  begin
  7  v_query1 := 'drop sequence unqid';
  8  v_query2 := 'create sequence unqid start with 1 increment by 1 minvalue 1';
  9  SELECT COUNT(*)
10  INTO V_COUNT
11  FROM USER_SEQUENCES
12  WHERE SEQUENCE_NAME = 'UNQID';
13
14  IF V_COUNT = 0 THEN
15  execute immediate v_query2;
16  ELSE
17  execute immediate v_query1;
18  execute immediate v_query2;
19  END IF;
20
21  SELECT distinct MODULE_ID INTO V_MOD FROM DUMMY WHERE ID = P_ID;
22
23  update dummy
24  set P_order = 0, status = 'D'
25  WHERE ID = P_ID
26  and module_id = v_mod;
27  --COMMIT;
28
29  execute immediate 'UPDATE DUMMY SET P_ORDER = UNQID.NEXTVAL WHERE MODULE_ID = V_MOD AND STATUS = ''A''';
30  --COMMIT;
31
32  END PRO_SEQ_ARRNGE;
33  /
Procedure created.
SQL> exec PRO_SEQ_ARRNGE(10);
BEGIN PRO_SEQ_ARRNGE(10); END;
ERROR at line 1:
ORA-00904: "V_MOD": invalid identifier
ORA-06512: at "SCOTT.PRO_SEQ_ARRNGE", line 29
ORA-06512: at line 1The problem is that you can't refer to a local variable like V_MOD in a dynamic SQL statement. You'd need to use a bind variable
SQL> ed
Wrote file afiedt.buf
  1   CREATE OR REPLACE PROCEDURE PRO_SEQ_ARRNGE(P_ID NUMBER) AS
  2  V_MOD DUMMY.MODULE_ID%TYPE;
  3  v_query1 varchar2(200);
  4  v_query2 varchar2(200);
  5  V_COUNT NUMBER;
  6  begin
  7  v_query1 := 'drop sequence unqid';
  8  v_query2 := 'create sequence unqid start with 1 increment by 1 minvalue 1';
  9  SELECT COUNT(*)
10  INTO V_COUNT
11  FROM USER_SEQUENCES
12  WHERE SEQUENCE_NAME = 'UNQID';
13  IF V_COUNT = 0 THEN
14  execute immediate v_query2;
15  ELSE
16  execute immediate v_query1;
17  execute immediate v_query2;
18  END IF;
19  SELECT distinct MODULE_ID INTO V_MOD FROM DUMMY WHERE ID = P_ID;
20  update dummy
21  set P_order = 0, status = 'D'
22  WHERE ID = P_ID
23  and module_id = v_mod;
24  --COMMIT;
25  execute immediate 'UPDATE DUMMY SET P_ORDER = UNQID.NEXTVAL WHERE MODULE_ID = :1 AND STATUS = ''A'''
26    using v_mod;
27  --COMMIT;
28* END PRO_SEQ_ARRNGE;
29  /
Procedure created.
SQL> exec pro_seq_arrnge(10);
PL/SQL procedure successfully completed.Of course, I'm not using the SYSTEM schema. You should really, really avoid SYS and SYSTEM-- things often work differently there than they do normally. I also join the other folks that have tried to help you in suggesting that creating a sequence dynamically in a procedure is a very poor idea and almost certainly indicates that you need to reconsider your design.
Justin

Similar Messages

  • How to use dynamic query for Result table

    Hello Experts,
    I want to use dynamic query and then display the result in the assignment block.
    Using dynamic query BTQAct and BTQRAct and base on some search criteria i want tofilter and then append the result in the result table of that custom context node, and then it should display the result in the view in UI.
    SO can you please provide me the samplle code on how to use the dynamic query and append in the result table.
    Regards.

    Hi,
    Please find below sample code:
    data:  query         TYPE REF TO cl_crm_bol_dquery_service,
               result        TYPE REF TO if_bol_bo_col.
    DATA: lt_params       TYPE crmt_name_value_pair_tab,        
               lwa_params      TYPE crmt_name_value_pair.             
    query = cl_crm_bol_dquery_service=>get_instance( 'BTQAct' ). " Get instance of dynamic query
    Set general query parameter for maximum number of hits
          lwa_params-name = 'MAX_HITS' .
          lwa_params-value = '50'.
          APPEND lwa_params TO lt_params.
          query->set_query_parameters( it_parameters = lt_params ).
          query->add_selection_param( iv_attr_name = 'OBJECT_ID'
                                                    iv_sign      = 'I'
                                                    iv_option    = 'EQ'
                                                    iv_low       = <lv_objectid>
                                                    iv_high      = '' ). " Set your search criteria. Repeat this code if you have multiple parameters
    "You can find possible search options for a query object in  GENIL_BOL_BROWSER
    result ?= query->get_query_result(  ).   " Get result from your search query
    me->typed_context-> <your result context node>->set_collection( result ). 
    Here you will have to create a context node in your view which would refer to query result object like for BTQAct its BTQRAct                      
    Hope this helps.
    e Regards,
    Bhushan

  • Finding minimum value in each row using dynamic query

    need to find the minimum and maximum value from each row using dynamic query
    [from curr] will be given as input
    Tuky

    DECLARE @t TABLE(a INT,b INT,c INT);
    INSERT @t VALUES(1,2,3),(9,8,7),(4,6,5);
    SELECT *
    ,      (   SELECT  MAX(val) 
               FROM    (VALUES (a)
                           ,   (b)
                           ,   (c)
                       ) AS value(val)
           ) AS MaxVal 
    ,      (   SELECT  MIN(val) 
               FROM    (VALUES (a)
                           ,   (b)
                           ,   (c)
                       ) AS value(val)
           ) AS MinVal 
    FROM @t;
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • How to use three part name with using dynamic query.

    Dear all, (sqlserver 2008 express r2)
    q1)following is showing error, is it possible to accomplish the task with out using dynamic query.
    DECLARE @A VARCHAR(100)
    DECLARE @A1 VARCHAR(100)
    SET @A='DB1'
    SET @A1='DBO'
    SELECT * FROM @[email protected]
    q2) table value function is not accepting dynamic query , is there any way to do this task.
    yours sincerley

    Certain parts in an SQL query like FROM tablename cannot be local variables. In such a case, dynamic SQL can be applied:
    http://www.sqlusa.com/bestpractices/dynamicsql/
    As noted above, more information needed to decide if dynamic SQL the correct solution in this instance.
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • 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

  • Create table problem using Dynamic Query

    Hi all,
    I want to create a temporary table within a stored procedure so I decided to do it using a dynamic query:
    create or replace procedure p1
    as
    begin
    execute immediate 'CREATE GLOBAL TEMPORARY TABLE tt(id number(2))';
    end;
    / It created successfuly but when I execute that procedure I got:SQL> exec p1;
    BEGIN p1; END;
    ERROR at line 1:
    ORA-01031: insufficient privileges
    ORA-06512: at "SCOTT.P1", line 4
    ORA-06512: at line 1 While I can create that table using the same user without any problem!
    My question is:What privilege should I grant to user(minimum of privileges please! ) to execute that procedure successfuly?
    -Thanks

    Hi,
    To say a little bit more about Nicolas' answer:
    SQL> grant create table to scott;
    This is the right answer, but you might wonder why you have to do so if you usually can create tables with this user..
    11:59:19 TEST.SQL>CREATE USER UTEST
    11:59:28   2  IDENTIFIED BY UTEST;
    User created.
    11:59:35 TEST.SQL>CREATE ROLE RTEST;
    Role created.
    11:59:40 TEST.SQL>GRANT RTEST TO UTEST;
    Grant succeeded.
    11:59:45 TEST.SQL>GRANT CREATE SESSION TO RTEST;
    Grant succeeded.
    11:59:54 TEST.SQL>GRANT CREATE TABLE TO RTEST;
    Grant succeeded.
    12:00:03 TEST.SQL>GRANT UNLIMITED TABLESPACE TO UTEST;
    Grant succeeded.
    12:00:17 TEST.SQL>CREATE PROCEDURE UTEST.CT_TEST
    12:00:32   2  IS
    12:00:33   3  BEGIN
    12:00:35   4  EXECUTE IMMEDIATE 'CREATE TABLE UTEST.TTEST (A NUMBER)';
    12:00:56   5  END;
    12:00:58   6  /
    Procedure created.
    12:00:59 TEST.SQL>EXEC UTEST.CT_TEST;
    BEGIN UTEST.CT_TEST; END;
    ERROR at line 1:
    ORA-01031: insufficient privileges
    ORA-06512: at "UTEST.CT_TEST", line 4
    ORA-06512: at line 1
    12:01:06 TEST.SQL>GRANT CREATE TABLE TO UTEST;
    Grant succeeded.
    12:01:15 TEST.SQL>EXEC UTEST.CT_TEST;
    PL/SQL procedure successfully completed.Don't forget that when you're using PL/SQL, privileges granted via roles are ignored!
    Regards,
    Yoann.

  • Ref Cursor Using Dynamic Query

    Hi,
    I need to use the ref cursor to fetch result from dynamic query.
    e.g.
    Open ref_test_tbl for Select * from tbl1 where tbl1.field1= :1
    and tbl1.field2 =:2 using i_v1,i_v2;
    The thing is i_v1, i_v2 are dynamic.
    i.e. using clause can include i_v3, i_v4 also.
    How to include dynamic variables in the using clause.
    thanks

    > How to include dynamic variables in the using clause.
    Cannot using a ref cursor.. (and anyone that post code that writes dynamic PL/SQL in order to achieve this, I will call an idiot).
    What you should be using in PL/SQL is a DBMS_SQL cursor. This allows you to create a fully dynamic SQL statement with bind variables. E.g.
    select * from tbl1 where col1 = :1
    select * from tbl1 where col2 = :1 order by 2
    select * from tbl1 where col3 between :0 and :1
    Using this dynamically created SQL statement, you can parse it using DBMS_SQL, determine the number of bind variables, and bind each of these dynamically.
    You can then execute the SQL and again, dynamically, determine just what the projection of the cursor is. How many columns are returned, their names, data types, precision and so on.
    This is what APEX (see http://apex.oracle.com) use extensively in order to run SQLs and render these as reports - all dynamically.
    DBMS_SQL is detailed in the [url http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_sql.htm#BABEDAHF]Oracle® Database PL/SQL Packages and Types Reference manual.

  • 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

  • Cannot use sqlplus variable in create sequence statement

    Hello!
    I would like to create a sequence object starting with a number retrieved from a select statement:
    var max_resp_no number;
    begin
    select max(substr(resp_no,2)) into :max_resp_no from brc_mast
    where substr(resp_no,1,1)='Z';
    end;
    print max_resp_no;
    drop sequence p659_resp;
    create sequence p659_resp start with :max_resp_no;
    It tells me that :max_resp_no is an 'invalid number';
    TIA,
    habeeb

    You need to do this entirely in PL/SQL. You can either create a procedure, or use an anonymous block. The procedure version is below. Just change the CREATE to a DECLARE to get an anonymous block.
    CREATE OR REPLACE PROCEDURE new_seq IS
    max_resp_no NUMBER;
    BEGIN
    SELECT to_number(MAX(SUBSTR(resp_no,2)))
    INTO max_resp_no
    FROM brc_mast
    WHERE SUBSTR(resp_no,1,1)='Z';
    EXECUTE IMMEDIATE 'DROP SEQUENCE p659_resp';
    EXECUTE IMMEDIATE 'CREATE SEQUENCE p659_resp START WITH '|| max_resp_no;
    END;
    SQL> CREATE SEQUENCE p659_resp START WITH 1;
    Sequence created.
    SQL> SELECT p659_resp.nextval from dual;
       NEXTVAL
             1
    SQL> SELECT * FROM brc_mast;
    RESP_
    Z001
    Z002
    Z003
    Z075
    SQL> exec new_seq;
    PL/SQL procedure successfully completed.
    SQL> select p659_resp.nextval from dual;
       NEXTVAL
            75Note that the user creating this procedure will need to have CREATE SEQUENCE granted explicitly for the procedure to work. The anonymous block version should work if CREATE SEQUENCE is granted through a role.
    John

  • How to use dynamic query for this ??

    hi , i am new to ABAP. i got a requirement to write  dynamic query for the following code.
    kindly address. two set of queries are same.but condition is different.
    .IF p_psd EQ ' '.
    *C--End of change DF 1232137- (Transport # :CIDK980530 )
    *C--FETCH THE Deliverd Quantiity and Material Number
        SELECT aufnr "ORDER number
               wemng "Quantity of goods received for the order item
               matnr "MATERIAL NUMBER
               pwerk "PLANT
               dauat "Order Type
               FROM afpo
               INTO TABLE t_afpo
               WHERE aufnr IN s_order
               AND   wemng IN s_dqt
               AND   matnr IN s_matnr
               AND   pwerk IN s_plant
               AND   dauat = c_ro.
        IF sy-subrc = 0.
          SORT t_afpo BY aufnr matnr pwerk.
    *C--FETCH THE OBJECT NUMBER
          SELECT aufnr "ORDER number
                 objnr "Object number
                 FROM aufk
                 INTO TABLE t_aufk
                 FOR ALL ENTRIES IN t_afpo
                 WHERE aufnr = t_afpo-aufnr.
          IF sy-subrc = 0.
            SORT t_aufk BY aufnr objnr.
    *C--FETCH THE Target Quantiity
            SELECT aufnr "ORDER number
                   gamng "Total order quantity target quantity
                   FROM afko
                   INTO TABLE t_afko
                   FOR ALL ENTRIES IN t_afpo
                   WHERE aufnr = t_afpo-aufnr
                   AND   gamng IN s_tqt.
            IF sy-subrc = 0.
              SORT t_afko BY aufnr .
            ENDIF.
          ENDIF.
        ELSE.
          MESSAGE text-e03 TYPE c_s. " No data for the selection criteria
          LEAVE LIST-PROCESSING.
        ENDIF.
    *C--Begin of change DF 1232137- (Transport # :CIDK980530 )
      ENDIF.
      IF p_psd EQ c_x.
        SELECT aufnr "ORDER number
               wemng "Quantity of goods received for the order item
               matnr "MATERIAL NUMBER
               pwerk "PLANT
               dauat "Order Type
               FROM afpo
               INTO TABLE t_afpo
               WHERE aufnr IN s_order
               AND   wemng > 0
               AND   matnr IN s_matnr
               AND   pwerk IN s_plant
               AND   dauat = c_ro.
    if sy-subrc = 0.
    *C--FETCH THE OBJECT NUMBER
        IF  NOT t_afpo[] IS INITIAL.
          SORT t_afpo BY aufnr matnr pwerk.
          SELECT aufnr "ORDER number
                 objnr "Object number
                 FROM aufk
                 INTO TABLE t_aufk
                 FOR ALL ENTRIES IN t_afpo
                 WHERE aufnr = t_afpo-aufnr.
          IF sy-subrc = 0.
            SORT t_afko BY aufnr gamng.
          ELSE.
            MESSAGE text-e03 TYPE c_s. " No data for the selection criteria
            LEAVE LIST-PROCESSING.
          ENDIF.
        ENDIF.
        IF NOT t_afpo[] IS INITIAL.
    *C--FETCH THE Target Quantiity
          SELECT aufnr "ORDER number
                 gamng "Total order quantity target quantity
                 FROM afko
                 INTO TABLE t_afko
                 FOR ALL ENTRIES IN t_afpo
                 WHERE aufnr = t_afpo-aufnr
                 AND   gamng <> t_afpo-wemng .
          IF sy-subrc = 0.
            SORT t_afko BY aufnr gamng.
          ELSE.
            MESSAGE text-e03 TYPE c_s. " No data for the selection criteria
            LEAVE LIST-PROCESSING.
          ENDIF.
        ENDIF.
      ELSE.
        MESSAGE text-e03 TYPE c_s. " No data for the selection criteria
        LEAVE LIST-PROCESSING.
      ENDIF.
    Edited by: Thomas Zloch on Jan 5, 2011 1:30 PM please use code tags

    Hi friend,
    Try using MACRO and dynamic WHERE condition.
    Group simialr Select statements under a Macro.
    Build a dynamic where by checking conditions
    Call macro passing dynamic where condition.
    TABLES afpo.
    DATA: str TYPE string.
    *Macro definition
    DEFINE operation.
      select single *
           from afpo into afpo
           where (&1).    " Dynamic condition
    END-OF-DEFINITION.
    *Build dynamic WHERE by checking some conditions
    *If conditon 
    CONCATENATE 'AUFNR = ''000000700008''' 'AND POSNR = ''0001''' INTO str SEPARATED BY space.
    *Else
    CONCATENATE 'AUFNR = ''000000700008''' 'AND POSNR = ''0002''' INTO str SEPARATED BY space.
    *Endif.
    *Call Macro passing dynamic WHERE condition
    operation str.

  • Help! Inaccessible iterator when using dynamic query

    Hi!
    I have a problem retreiving results from a dynamic query into sqlj iterator.
    I consulted the Oracle App Dev Guide and Oracle SQLJ Dev Guide and wrote the following code:
    <PRE>
    package pmServer;
    #sql iterator LocIterator (int id, String name);
    public class pmRISDImpl
    public int GetLocations(...)
    LocIterator locIt;
    String q = "select ID, NAME from PMADM.LOCATIONS";
    #sql
    BEGIN
    open :OUT locIt for :q;
    END;
    </PRE>
    When I try to compile it using tools provided by JDeveloper ver 3.2.2.(Build 915) for JDK 1.2.2 I get error for #sql statement:
    Inaccessible Java type for host item locIt (at position #1): pmServer.LocIterator
    and warning:
    Type pmServer.LocIterator of host item locIt (at position #1) is not permitted in JDBC. This will not be portable.
    Althow the code is identcal to those demonstrated in Oracle document "Oracle8 i
    SQLJ Developers Guide and Reference
    Release 3 (8.1.7)
    July 2000
    Part No. A83723-01" pp 12-67 (PL/SQL in SQLJ for Dynamic SQLDynamicDemo.sqlj). There it looks like
    <PRE>
    private static void dynamicSelectMany(String what_cond)
    throws SQLException {
    System.out.println("dynamic multi-row query on table emp");
    Employees empIter;
    // table/column names cannot be bind args in dynamic PL/SQL, so
    // build up query as Java string
    String query = "select ename, sal from emp " +
    (((what_cond == null) &#0124; &#0124; (what_cond.equals(""))) ? "" :
    (" where " + what_cond)) +
    "order by ename";
    #sql {
    begin
    open :OUT empIter for -- opening ref cursor with dynamic query
    :query;
    -- can have USING clause here if needed
    end;
    while (empIter.next()) {
    System.out.println("Employee " + empIter.ename() +
    " has salary " + empIter.sal() );
    empIter.close();
    </PRE>
    Please guide me what should I do to get it working.
    null

    In the CAST statement the SQLJ runtime must be able to produce an instance of you SQLJ iterator using Java reflection.
    This necessitates that the iterator class must be accessible by public.
    You have two options:
    (1) Declare the iterator public. This requires that you put it in its own file LocIterator.sqlj:
    #sql public iterator LocIterator (int id, String name);
    (2) Declare the iterator as an inner class. In this case you want to make it public static (that is it does not require an instance of the outer class in scope). You might write the following.
    package pmServer;
    public class pmRISDImpl
    #sql public static iterator LocIterator (int id, String name);
    (3) If you are using Oracle 9i you have another option. You can embed dynamic SQL fragments directly in your SQLJ code and do not need to use the CAST:
    public int GetLocations(...)
    LocIterator locIt;
    String q = "PMADM.LOCATIONS";
    #sql locIt = { select ID, NAME from :{q} }; // Note new syntax :{q} for embedding SQL source code
    }

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

  • Create cursor using dynamic query

    Hi,
    I declare a query:
    l_query VARCHAR2(32000):= 'select distinct '||:P_ITEM||' from OCM_CUSTOMER';
    How can i assign this query to cursor?
    I tried this, but failed.
    Declare
    l_query VARCHAR2(32000):= 'select distinct '||:P_ITEM||' from OCM_CUSTOMER';
    CURSOR l_cur IS l_query;
    Begin
    End
    thanks for help on this.

    Hello,
    You need to use a REF CURSOR for that (there are some examples in the Oracle docs). Here is a code example:
    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;Greetings,
    Roel
    http://roelhartman.blogspot.com/

  • How to get max date in variable using  dynamic query

    Hi,
    the following code gets all dates from sourcetable i want only max date , so i thought max function can be added and it will work
    but still i have to create a table for one value(scalar) can get it in any other effeciant way.
    declare
    TYPE date_string IS TABLE OF VARCHAR(1000);
    date_obj date_string;
    BEGIN
    EXECUTE IMMEDIATE 'SELECT to_char('''||day1||'-'||month1||'-'||year1||''') FROM '||source_schema||'.'|| sourcetable ||'' bulk collect INTO date_obj;
    FOR indx IN date_obj.FIRST..date_obj.LAST loop
    dbms_output.put_line(
    date_obj(indx));
    END loop;
    DBMS_OUTPUT.PUT_LINE('Sample output');
    END;
    yours sincerely

    944768 wrote:
    the following code gets all dates from sourcetableNo it doesn't. What is the datatype of day1, month1 and year1? They cannot be DATE datatypes otherwise your TO_CHAR would fail with all that concatenation going on. And your TO_CHAR is returning a VARCHAR2 datatype... so you cannot say that it is getting all dates... because there are no DATE datatypes returned. It's getting a lot of strings, but certainly not DATE's.
    i want only max date , so i thought max function can be added and it will work You can use the MAX function on a DATE datatype, but not on strings (at least not in the way you intend it to work).
    Converting it to a DATE before doing the MAX will allow you to get the maximum date (assuming the date format is correct)
    EXECUTE IMMEDIATE 'SELECT max(to_date(to_char('''||day1||'-'||month1||'-'||year1||'''),''DD-MM-YYYY'')) FROM  '||source_schema||'.'|| sourcetable ||'' bulk collect INTO date_obj;Then you will find have the other issues...
    a) you are then going to be fetching your DATEs in to a collection of VARCHAR strings. (Not even VARCHAR2, very poor). This should be DATE datatype
    b) you are bulk collecting into a collection, when you are using MAX which will return a single value in your example
    And you really should address the design issues:
    c) why are day, month and year, not being stored in the database as a single DATE datatype in the first place
    d) why does your code not know the name of the table it's querying requiring the use of very poor dynamic SQL techniques.
    e) why are you loading data in a collection in expensive PGA memory... what can't you do in SQL that requires you to collect the data into memory first?

  • How to reterive  content using dynamic query  through content repository

    Hello,
    i am reteriving content from content repository,using following tag:
    <pz:contentQuery query="PPF_Type='Forms' && SupportGroup='HR'" sortBy="cm_modifiedDate" max="5" id="HRForms"/>
    where SupportGroup='HR/IT/Finance'
    How can I get property value dynamically without hardcoding like above,instead i want it as follows:
    String formQuery="PPF_Type='" + typeName + "' && SupportGroup='" + groupName + "'";
    How can i get 'typeName' and 'groupName' as variable through jpf,if i have to display titles in same page.

    Hello,
    i am reteriving content from content repository,using following tag:
    <pz:contentQuery query="PPF_Type='Forms' && SupportGroup='HR'" sortBy="cm_modifiedDate" max="5" id="HRForms"/>
    where SupportGroup='HR/IT/Finance'
    How can I get property value dynamically without hardcoding like above,instead i want it as follows:
    String formQuery="PPF_Type='" + typeName + "' && SupportGroup='" + groupName + "'";
    How can i get 'typeName' and 'groupName' as variable through jpf,if i have to display titles in same page.

Maybe you are looking for