How to dynamically execute generated SQL statements using 11gR2 ?

Hello,
I'd like to know if it is possible to do what the following statement intended to do:
select * from (select replace('select empno from emp',
                             '') from dual);in other words, is it possible to dynamically generate and execute a select statement in a from clause ?
thank you for your help,
John
Edited by: 440bx on Jul 16, 2010 3:57 PM changed "generate" to "generated" in subject

Hello Aketi,
That is totally WICKED !!
I've been playing with the code you posted, pretty much since you did, trying to figure out how it works. I have some idea of how it works now but, I cannot figure out why I get the set of results, not once but TWICE.
When I run the query you posted above, this is what I get:
SQL> @getxml2
TABLE_NAME                          count
CLOB_EXAMPLE                            1
D42                                     1
DEPT                                    4
DEPT_2                                  0
DEPT_ACCIDENTS                          6
DEPT_EAST                               2
... some tables deleted to shorten the output
T1                                      1
T10                                    10
T100                                    0
22 rows selected.
TABLE_NAME                          count
CLOB_EXAMPLE                            1
D42                                     1
DEPT                                    4
DEPT_2                                  0
DEPT_ACCIDENTS                          6
DEPT_EAST                               2
... some tables deleted to shorten the output
T1                                      1
T10                                    10
T100                                    0
22 rows selected.
SQL>The result is shown TWICE. I cannot figure out why. Any ideas as to why the result is shown twice ? (I ran the statement from SQL*Plus and started a fresh instance of SQL*Plus to ensure that no settings from previous scripts would be the cause).
Thank you for your help, great little piece of code!
John.
Edited by: 440bx on Jul 16, 2010 5:30 PM
Edited by: 440bx on Jul 16, 2010 5:31 PM - corrected name in Hello greeting
Edited by: 440bx - 11gR2 on Jul 17, 2010 2:55 AM - corrected misspelling
Edited by: 440bx - 11gR2 on Jul 17, 2010 2:56 AM - corrected another misspelling

Similar Messages

  • How to examine the generated SQL statement in Receiver JDBC Adapter

    I have been searching this forum how to display te generated sql statement (by the jdbc receiver adapter).
    The only suggestion is to use RWB, but I was unable to find any details about how to do so.
    Any help is appreciated

    Hi,
    To add, u can see the SQL Statements in Audit log of RWB.
    Select Message Monitoring-> Adapter Engine. choose ur entry and click on Details option button, u can see the SQL Statements in Audit Log.
    Regards,
    Sudharshan
    Message was edited by:
            Sudharshan Aravamudan

  • How to dynamic create Select SQL statements.

    Hi frnds,
    I want to make a SELECT statement in which all values I will get dynamically. Like i have two fields on selection screen, one for table name and one for field name. Now I need to make my ITAB according to the table selected and field name selected. So finally my ITAB will be having the field which I chosen from selection screen.
    Now how can I make a dynamic ITAB and how to create a dynamic SELECT statement?
    It wud be great if you can help me.
    Thanks
    Arpit

    Here is a sample program....
    This will get you started in programming a dynamic internal table as well as dynamic select.
    report zrich_0002.
    type-pools: slis.
    field-symbols: <dyn_table> type standard table,
                   <dyn_wa>,
                   <dyn_field>.
    data: alv_fldcat type slis_t_fieldcat_alv,
          it_fldcat type lvc_t_fcat.
    type-pools : abap.
    data : it_details type abap_compdescr_tab,
           wa_details type abap_compdescr.
    data : ref_descr type ref to cl_abap_structdescr.
    data: new_table type ref to data,
          new_line  type ref to data,
          wa_it_fldcat type lvc_s_fcat.
    selection-screen begin of block b1 with frame title text .
    parameters: p_table(30) type c.
    selection-screen end of block b1.
    * Get the structure of the table.
    ref_descr ?= cl_abap_typedescr=>describe_by_name( p_table ).
    it_details[] = ref_descr->components[].
    loop at it_details into wa_details.
      clear wa_it_fldcat.
      wa_it_fldcat-fieldname = wa_details-name .
      wa_it_fldcat-datatype = wa_details-type_kind.
      wa_it_fldcat-intlen = wa_details-length.
      wa_it_fldcat-decimals = wa_details-decimals.
      append wa_it_fldcat to it_fldcat .
    endloop.
    * Create dynamic internal table and assign to FS
    call method cl_alv_table_create=>create_dynamic_table
                 exporting
                    it_fieldcatalog = it_fldcat
                 importing
                    ep_table        = new_table.
    assign new_table->* to <dyn_table>.
    * Create dynamic work area and assign to FS
    create data new_line like line of <dyn_table>.
    assign new_line->* to <dyn_wa>.
    * Select Data from table.
    select * into corresponding fields of table <dyn_table>
               from (p_table).
    * Write out data from table.
    loop at <dyn_table> into <dyn_wa>.
      do.
        assign component  sy-index  of structure <dyn_wa> to <dyn_field>.
        if sy-subrc <> 0.
          exit.
        endif.
        if sy-index = 1.
          write:/ <dyn_field>.
        else.
          write: <dyn_field>.
        endif.
      enddo.
    endloop.
    Regards,
    Rich Heilman
    Message was edited by: Rich Heilman

  • How to execute the *.sql when using occi  and vc

    help me!
    i must to initialize the remote database using the file of sql,
    for example:
    the file is ss.sql;
    and it is
    "DECLARE
    row integer := 0;
    user varchar2(256);
    BEGIN
    user := '&1';
    dbms_java.grant_policy_permission('PUBLIC', 'SYS',
    'java.lang.RuntimePermission', 'loadLibrary.*', row);
    dbms_java.grant_permission(user, 'SYS:java.lang.RuntimePermission',
    'loadLibrary.orawcom10', null);
    dbms_java.disable_permission(row);
    dbms_java.delete_permission(row);
    EXCEPTION
    WHEN OTHERS THEN
    IF row > 0 THEN
    dbms_java.disable_permission(row);
    dbms_java.delete_permission(row);
    END IF;
    RAISE;
    END;"
    i use the occi statement
    Environment * env;
    Connection * conn;
    Statement * stmt;
    env=Environment::createEnvironment(Environment::DefaultEnvironment);
    conn=env->createConnect(user_name,pwd,db_name);
    string sqlstmt=''BEGIN ss.sql;END";
    stmt=conn->createStatement(sqlstmt);
    it is wrong
    how do i change the sql statement???

    Hi,
    Instead of having the PL/SQL code as an anonymous block, you can create
    a procedure and then execute it through OCCI.
    For example:
    create or replace procedure my_proc
    is
    row integer := 0;
    user varchar2(256);
    begin
    --code here...
    end;
    I assume this code will be in ss.sql. Compile this procedure in
    your schema and then form the sqlstmt in OCCI this way:
    Statement *stmt = con->createStatement("BEGIN my_proc; END;") ;
    Rgds.
    Amogh

  • How to execute multiple sql statements

    hi all
    i am wondering if i can execute multiple sql statements in one shot with >> execute immediate command
    for example:
    i define the variable as X := sql statement
    Y := sql statement
    z := sql statement
    can i do execute immediate (X,Y, Z);
    if yes how ?? and if not any possible alternate
    thanks

    Starting with Ganesh's code
    DECLARE
       l_statement                 VARCHAR2 (2000);
       v_passwd                    VARCHAR2 (200);
       v_username                  VARCHAR2 (200) := 'test';
       v_pwd_key                   VARCHAR2 (200) := 'lwty23';
       v_dblink_name               VARCHAR2 (2000);
       v_dblink_drop               VARCHAR2 (2000);
       v_dblink_create             VARCHAR2 (2000);
       v_dblink_check_connection   VARCHAR2 (2000);
       l_number                    NUMBER;
    BEGIN
       --<<c_instance>>
       FOR c_instance IN (SELECT *
                            FROM v_oracle_instances
                           WHERE environment = 'Developement')
       LOOP
          SELECT encpwd_owner.display_db_encpwd (v_username,
                                                 c_instance.host_name,
                                                 c_instance.instance_name,
                                                 v_pwd_key)
            INTO v_passwd
            FROM DUAL;
          v_dblink_name := c_instance.host_name || '_' || c_instance.instance_name;
          v_dblink_create :=
                ' CREATE DATABASE LINK '
             || v_dblink_name
             || ' CONNECT TO '
             || v_username
             || ' '
             || 'IDENTIFIED BY '
             || v_passwd
             || ' USING'
             || ' ''(DESCRIPTION=
    (ADDRESS=(PROTOCOL=TCP)(HOST= '
             || c_instance.host_name
             || ')(PORT='
             || c_instance.LISTENER_PORT
             || '))(CONNECT_DATA=(SID='
             || c_instance.instance_name
             || ')))''';
          v_dblink_check_connection := 'select 1 from global_name@' || v_dblink_name || '.QCM';    --- Notice this change. I am simply selecting 1. That should be enough to test the database link.
          v_dblink_drop := 'drop database link ' || v_dblink_name || '.QCMTLAF';
          -- l_statement := 'BEGIN ' || v_dblink_create ';' || v_dblink_check_connection ';' || v_dblink_drop '; END ;'
          BEGIN
              EXECUTE IMMEDIATE (v_dblink_create);
              DBMS_OUTPUT.PUT_LINE ('DB Link ' || v_dblink_name || ' Created');
         EXCEPTION
            WHEN others THEN
               dbms_output.put_line( 'Failed to create the database link ' || v_dblink_name  );
               dbms_output.put_line( dbms_utility.format_error_backtrace() );
               INSERT INTO error_table( column_list )
                 VALUES( <<list of values>> );
         END;
          EXECUTE IMMEDIATE (v_dblink_check_connection) INTO l_number;    --- Notice this.
          DBMS_OUTPUT.PUT_LINE ('DB Link ' || v_dblink_name || ' Tested');
          BEGIN
             EXECUTE IMMEDIATE (v_dblink_drop); 
             DBMS_OUTPUT.PUT_LINE ('DB Link ' || v_dblink_name || ' Dropped');
          EXCEPTION
             WHEN others THEN
               dbms_output.put_line( 'Failed to drop the database link ' || v_dblink_name  );
               dbms_output.put_line( dbms_utility.format_error_backtrace() );
               INSERT INTO error_table( column_list )
                 VALUES( <<list of values>> );
         END;
       END LOOP;
    END;But I agree with the point that others have brought up that it really doesn't make sense to create and drop a database link like this.
    Justin

  • Executing multiple SQL statements fails using ODBC

    Executing multiple SQL statements will fail with error 'ORA-00911 invalid character' when connecting to an Oracle database using ODBC driver version 8.01.07.00.
    When I use either my application or the Oracle ODBC Test client utility connecting using ODBC driver version 8.01.07.00 I can only get a single CALL statement (as shown below) to execute:
    CALL BHInsert (TO_DATE('2003.07.23 10:04:28','YYYY.MM.DD HH24:MI:SS'),'BATCH_ID','1:CLS_FRENCHVANILLA-1','
    ','Event File
    Name','\\KILLIANS\BATCHCTL\SampleDemo1\JOURNALS\1.evt','','AREA1','','','','','','1','','','','','',' ','');
    When I try to execute the following string with multiple CALL statements (as shown below) it fails with the following error being returned - ORA-00911: invalid character
    CALL BHInsert (TO_DATE('2003.07.23 10:04:28','YYYY.MM.DD HH24:MI:SS'),'BATCH_ID','1:CLS_FRENCHVANILLA-1','
    ','Event File
    Name','\\KILLIANS\BATCHCTL\SampleDemo1\JOURNALS\1.evt','','AREA1','','','','','','1','','','','','',' ','');
    CALL BHInsert (TO_DATE('2003.07.23 10:04:28','YYYY.MM.DD
    HH24:MI:SS'),'BATCH_ID','1:CLS_FRENCHVANILLA-1','Version','Recipe Header','1.0','','AREA1',' ','
    ','','','','1','','','','','',' ','');
    CALL BHInsert (TO_DATE('2003.07.23 10:04:28','YYYY.MM.DD
    HH24:MI:SS'),'BATCH_ID','1:CLS_FRENCHVANILLA-1','Version Date','Recipe Header','5/18/2001 1:28:32
    PM','','AREA1',' ',' ','','','','1','','','','','',' ','');
    CALL BHInsert (TO_DATE('2003.07.23
    10:04:28','YYYY.MM.DD HH24:MI:SS'),'BATCH_ID','1:CLS_FRENCHVANILLA-1','Author','Recipe Header','Mark
    Shepard','','AREA1',' ',' ','','','','1','','','','','',' ','');
    I've tried adding a line feed in addition to the space at the end of each call but that doesn't seem to help. Also have tried unsuccessfully to change the seperator used between each call using various valid continuation characters.
    Executing multiple CALL statements from within Oracle's SQL Worksheet connecting as the same user and password, as my application executes successfully. However when I try this from within the Oracle ODBC test client, it fails with the same ORA-00911 error that I'm seeing in my application.
    I'm currently trying the more recent ODBC drivers, however any ideas or suggestions would be greatly appreciated.

    Can you take the begin ... end block and run it using SQL*Plus?
    I can't think of any documentation that would specifically answer this question. I'm sure if you read & absorbed the ODBC Programmers Reference (2000+ pages) you'd be able to find out, but I don't know of a quick way to find out.
    You can enable SQL*Net tracing. There are a fair number of options for enabling this tracing-- http://tahiti.oracle.com has all the Oracle manuals online, which should give you enough info to configure exactly what you want.
    I would suggest, however, that you look into more performant/ scalable alternatives rather than going too far down this path. A block with lots of SQL statements with literals isn't going to make your database happy even if you get it to work.
    Justin

  • How to execute multiple SQL statements thru frontend?

    With SQL Server database, you can execute multiple SQL statements.
    Ex.
    SQLCommand cmd = new SQLCommand();
    cmd.CommandText = "SELECT * FROM EMP; SELECT * FROM DEPT";
    cmd.ExecuteXXX();
    Note that for SQL Server, ";" (semocolon) is used as a separator.
    What separator is required for Oracle ? Or rather, can I execute multiple SQL statements against Oracle database (10g) ?
    (Why I want to do it is a totally diff. subject !)
    Thanks,
    Ami.

    Hello,
    You could use an anonymous PL/SQL block to batch multiple statements.
    If you want to use SELECT statements, you would open a REF CURSOR for each SELECT and return the REF CURSOR to your application. INSERT, UPDATE, and DELETE statements can just be passed as is.
    A simple REF CURSOR example might look like:
    begin
      open :v_refcursor1 for select * from emp;
      open :v_refcursor2 for select * from dept;
    end;Where v_refcursor1 and v_refcursor2 are parameters defined as a REF CURSOR type.
    Hope that helps a bit...
    - Mark

  • Not able to View generated SQL statement

    Hi,
    In order to view the generated SQL statement in Receiver JDBC Adapter,
    i have done logSQLStatement as true in  CC still not able to view in RWB,
    also mesg protocol i m using in CC is "xml sql format", is it bcos of this i am not able to ?
    If yes, then how can i see that sql string?
    Regards,
    Pratibha

    Pratibha,
    In our JDBC scenario the message protocol is also set to XML SQL Format
    The Integration Process has a mapping step of type XSL that uses an Imported Archive to create the SQL select statement.  Then there is a synchronous Send step for the JDBC component
    Both this SQL statement and the returned SQL result are available in the XML message monitor SXMB_MONI
    Regards,
    Mike

  • UD Connect Generated SQL Statement

    Hi All,
    Can anyone tell me if it's possible to influence the generated SQL statement?  We need to be able to use the order by clause so as to get the records in the correct order.
    Any help much appreciated.
    Thanks
    Craig

    Hi
    Yes its possible in THIS WAY.
    CASE-1
    In UD Connect we have the DATA in a BASE TABLE. When we execite the under like DATASOURCE  (UD-CONNECT). The dependant Info PACK brings the complete data to PSA. After the DATA LANDS in PSA. We can sort out in the same way how can SORT in the SQL Statement method. But to do this you have to PUT a Start routine at infopack level.
    Case-2
    You have to use a store procedure out side the SAP BI .

  • Patterns to execute a SQL Statement from a Droplet (select)

    Hi,
    I need to perform a query on a table, Example: select * from ARF_QUERY "the database used is Oracle. I would like to know if the atg has some
    standard method to perform this database connection and execute the SQL statement from a Droplet (select).
    Thank.

    I dont think there is any generic droplet to run a select query directly against a table.
    However, there are various lookup droplets available that run on the repositories.
    Like /atg/targeting/RepositoryLookup droplet. you can run it for specific id or for all.
    You might want to have a look at it in documentation of how exactly to use it.
    Thanks

  • How can I write a SQL statement which checks if a table exists?

    How can I write a SQL statement which tells me whether a table exists?

    execute an sql query: select * from <tablename>
    catch the exception n check whether the erroe code
    matches the one that occurs for table doesn't exist
    that's itHow is your answer any different from the one given in the first reply?
    It isn't.
    As WorkForFood says DatabaseMetaData has a bunch of methods for getting information about tables but this is more useful when you don't know the names of any of the tables.. it sounds like you do so I would concur SELECT from table is probably the quickest way to go. If it helps the Xopen error should be either S1000 or 42S01 (I think) but I would try and see if there is a specific vendor code for table not found/not exists error and check for that.

  • How could I find the SQL statement who get this message ?

    ORA-01555 caused by SQL statement below (Query Duration=11191 sec, SCN: 0x0854.723b9c32)
    ... How could I find the SQL statement who got this message ?
    Thanks, Paul

    ORA-01555 means that the UNDO/ROLLBACK space is not large enough.
    This occurs because the SELECT statement is attempting to read the UNDO, but the UNDO has been released (transactions have committed or rolled back) and reused.
    The following are SOME of the reasons I have seen this to occur:
    1) Updates in a loop, with commits happening in the same loop
    - this will mark the UNDO available quickly and quickly reuse it. Then when the SELECT wants to rebuild a block, the UNDO used to rebuild the block has been reused (solution, make the UNDO bigger)
    2) A SELECT cursor used to control a loop in which updates are performed, and a 'done' flag is marked against the current cursor record, and commits are performed at the end of each loop, prior to fetching the next record
    - same problem as above, but it hits the current process. Same solution
    3) A 'month end' activity spike occurs, and all sorts of transactions create updates. There is a report that reports the activity - amusingly it needs to start at the beginning of all the work and updates periodically by doing a huge SELECT up front. This is then used to drive a loop which attempts to get information from the various transactions that have been updated and committed. After a while, the SELECT gets an ORA-01555
    - same problem as above and same solution. Get a bigger UNDO segment.
    You say this only happens once a month. That should give a hint.
    I wouldn't bother with which SELECT statement, as much as which APPLICATIONs are being run when it happens.
    One way around this - use 10g and set the guaranteed retention period. All sorts of other things will break, by no more 1555. <g>

  • Executing the SQL statement is not allowed - Error

    I am getting "Executing the SQL statement is not allowed" for an INSERT cfquery that I'm running.  I checked the usual suspects:
    - DSN allows INSERT
    - I've seen reports online where certain field names or values are considered key words, so for protection CF blocks the query in this way (it would be nice if there was a different error message when it gets blocked this way vs. the DSN doesn't allow INSERT error message).  The field names and values were all benign strings, so it didn't seem like that.
    I took the same string for the query and ran it on another page and it ran fine (same DSN, too).

    SOLVED: I decided to enter this in here, just to get it into web searches for others since I couldn't find anything.
    - I was calling a function for one of the values in the query:  get_db_status_code("initialize")  Apparently CF parses the query to see if it's allowed BEFORE it runs the CFML in it, so something in that function name, or the parameter "initialize" was a key word that CF doesn't allow.  I moved the function call outside of the query and loaded a temp variable for use in the query and it then worked.

  • Execute Different SQL Statements Based On Day of Week

    I need to execute different sql statements based on the day of the week in Oracle 8i. In SQL Server, it's pretty simple. SELECT
    CASE DATEPART(dw,GETDATE())
    WHEN 4 THEN (SELECT COUNT(*) FROM ADR_VLDN )
    END
    In Oracle it should be something like this
    IF to_char(SYSDATE, 'D') = 2 THEN
    SELECT * FROM RSVP_FILE_PRCS WHERE ROWNUM = 1;
    ELSEIF to_char(SYSDATE, 'D') = 3 THEN
    SELECT * FROM RSVP_FILE_PRCS WHERE ROWNUM = 2;
    END IF;
    But this doesn't work. Does anyone have any ideas about how to do this in Oracle?

    805771 wrote:
    Yes, but I don't want to create 7 different jobs, one for each day of the week. Isn't there a way to do this in PL/SQL? It took me 10 seconds in SQL Server's TSQL.Yes you keep showing some TSQL syntax that obviously does not do what you are asking for.
    >
    SELECT
    CASE DATEPART(dw,GETDATE())
    WHEN 4 THEN (SELECT COUNT(*) FROM ADR_VLDN )
    ENDSo the equivalent in Oracle would be
    SQL> var n number
    SQL> begin
      2    if to_char(sysdate,'D') = '4' then
      3      select count(*) into :n from dual;
      4    end if;
      5  end;
      6  /
    PL/SQL procedure successfully completed.
    SQL> print n
             N
             1Also takes 10 seconds.

  • How to monitor worst performing sql statements

    Hi,
    I am new to oracle 9i release 2. I come from the Windows world, where we used sql server.
    When we performanced tested our product, we always monitor the worst performaning sql statement using the sql profiler. At the end of a 24 hour test, the profiler will list the sql statement with the longest execution time. What is the equivalent Oracle 9i tools that will allow me to monitor the worst performaning sql during a test that lasts between 10 to 24 hours?
    Thanks,
    Paul0al

    Besides statspack and OEM you have a few other options.
    If an SQL statement had been identified as performing poorly or a job that you can extract the SQL from then you have the option of explaining all the SQL statements and just reviewing the plans for reasonableness. You can also trace actual execution of the task or individual statemnts (alter session set sql_trace = true for basic 10046 event).
    When the SQL has not been identified in advance you can query the shared pool SQL areas for SQL statements that have relatively high physical, logical, or combined IO counts. Then you can perform tuning activities for these statements.
    HTH -- Mark D Powell --

Maybe you are looking for

  • Since upgrading to OSX 10.6.8, I am unable to use scp on a remote machine to copy files into my iMac.

    Any suggestions? However, I can use scp to copy files out from my iMac (10.6.8) . I can ssh into the iMac OK. I created a .profile in my iMac home directory with the single line "export TERM=xterm-color". This makes a difference to how scp behaves wh

  • Where do I find basic automator actions?

    I don't see simple actions such as "save" or "save as pdf" in the list of automator actions. where are they?

  • Saving as in PS3 after opening in LR3

    I import jpeg photos into LR3. I make adjustments and edit in PS3. After editing I try to save as jpeg. The drop down box only allows psd, tiff, png and a few other choices I never use. Is there some simple reason I can't save as jpeg in PS3? Thanks

  • Applying FixPacks in Eclipse

    Hi I am using CR for Eclipse. i am experiencing this bug: After setting the hyperlink target for the crystalreport viewer to _blank, clicking on a link in the report causes the link to open in the main viewer page - not in a new window. i realize the

  • Question about sysprep re-arranging desktop icons

    I can deploy my windows 7 image just fine, the copy profile is working as well, but I have setup the icons a specific way on the desktop on a couple of my images, and after deployment they always go back to the standard looking rows, and I lose all t