Dynamic SQL statement in a Procedure

Hi,
is it possible to use a variable in place of a column name in a sql statement inside a procedure. Or to create the whole statement as a sql statement and execute it (preferrably with parameters - rather than concatinating the values).
Thanks for any help or direction
Elliot

Turns out you can do the following very nicely (dynamic sql with parameterized values)
Declare
id number(10,0);
sql_stmt varchar2(300);
fieldName varchar2(30);
fieldValue varchar2(100);
id := 30;
fieldName := 'somecolumn';
fieldValue := 'some value';
sql_stmt := 'UPDATE myTable SET ' || fieldName || ' = :1 WHERE id = :2';
EXECUTE IMMEDIATE sql_stmt USING fieldValue, id;

Similar Messages

  • How can I execute Dynamic SQL statement in Forms?

    Hi All,
    I have to execute dynamic SQL statement from Forms
    Below statement I have to execute
    "EXECUTE IMMEDIATE v_stmt INTO v_return;".
    Googled for the same got results saying, Better use Database function or procedures to execute these Dynamic Statements but We want to execute in forms only.
    Can any one help me..
    Thanks,
    Madhu

    So in short you are trading code obfuscation for maintainability and the ability to share code between tools? If from somewhere else you need a procedure already implemented in database PL/SQL (and now ported to forms) this would mean you'd need to implement it in every other tool. In times where you might want to integrate your forms with $other_technology and putting stuff on the database is the first step to share functionality you just go the opposite way? And all that because someone is afraid that somebody might steal your source code? I am sorry to be blunt, but this is just plain stupid.
    Leaving aside that some things like Analytic Functions, Bulk processing or execute immediate are not even available in forms your software consists of how many LOC? How long does it take to bring a new developer up to speed with your source code? Imagine how long that would take for a developer who doesn't have coleagues who know their way around.
    And just so you know: I work for a ISV selling a closed-source product as well. We have 200+ customers all over the planet. We are well aware that wrapped packages can be reverse engineered. The premise is: stored procedures can be reused in every tool we have, if it makes sense to put stuff on the database by all means do it. If someone would want to reverse engineer our software I'd wish him good luck as some parts are implemented in such a hilarious complicated way I have troubles understanding them (and quite frankly I refuse to understand certain parts, but that's another story). I do work for almost 10 years for that ISV.
    In any case the possible solutions have already been mentioned: you have exec_sql, create_group_from_query and forms_ddl to execute dynamic SQL in forms whereas forms_ddl is a one way street and most certainly not the thing you need or want. Take a look at the documentation for the other 2 things.
    cheers

  • How to run dynamic SQL from an ODI procedure step

    I am on ODI 11.1.1.6.4. From within an ODI IKM step I have no problem running a procedure step like the following which calls a pl/sql procedure to get SQL text then later runs that code. Is there anyway to do the same from within an ODI procedure? I've tried a couple of variations and can not seem to get the parsing levels to resolve within a procedure like they resolve from within a KM step.
    <@
    /* Setup Java variables */
    String out_SQL = "";
    try
    java.sql.Connection sourceConnection = odiRef.getJDBCConnection("SRC");
    String sqltxt = "{call set_sql(?)}";
    java.sql.CallableStatement pstmt = sourceConnection.prepareCall(sqltxt);
         try
         pstmt.registerOutParameter( 1, java.sql.Types.VARCHAR);
         pstmt.execute();
    out_SQL = pstmt.getString(1);
         catch(java.sql.SQLException ex)
              errMessage = ex.getMessage();
              errMessage = errMessage.replace("'","");
         finally
              pstmt.close();
    catch(java.lang.Exception e)
         errMessage = e.getMessage();
         errMessage = errMessage.replace("'","");
    @>
    BEGIN
    -- The SQL that I want to run
    <@
    out.println(out_SQL);
    @>
    -- Error handling
    <@ if ( out_SQL.length() ==0 ) { @>
         raise_application_error(-20101, '<@=errMessage@>');
    <@ } else { @>
         dbms_output.put_line('Successful.');
    <@ } @>     
    END;
    ------

    Please understand that I know that I can do this all within PL/SQL -- I am explicitly doing it the way I have outlined because I want to better understand the parsing levels/behavior within ODI procedures and I want to understand why KMs steps behave differently.
    Another observation -- putting this all within a pl/sql block prevents ODI from properly capturing insert/update/delete row counts like it would if it were running a SQL statement.
    So the question remains -- is there a way to run a dynamic SQL statement in an ODI procedure where the SQL statement is generated from within an Oracle procedure call and then run as SQL within an ODI procedure step? Best would be if there is an example of how this can be done.

  • Help With SUBSTR in dynamic SQL statement

    Following is the dynamic SQL statement.
    EXECUTE IMMEDIATE 'UPDATE table_name pml
    SET pml.'|| con_fields.field ||' = SUBSTR(pml.'||con_fields.field||' ||'' ''||
    (SELECT pml1.'||con_fields.field||'
    FROM table_name pml1
    WHERE pml1.grp_id = '||los_concats.grp_id ||'
    AND pml1.row_id = '||los_concats.row_id||'
    AND pml1.loser_flg = ''Y''),1, '||con_fields.max_length||')
    WHERE pml.grp_id = '||los_concats.grp_id ||'
    AND pml.loser_flg IS NULL ';
    what it does is that it updates a particular field. This field is concatenated by a field of a similar record.
    My problem is with SUBSTR function. Since I am concatenating fields I do not want the field to be updated greater than max_length on that field, the reason why I use SUBSTR. the select query inside SUBSTR works alright with one of the AND condition in a WHERE clause not present. When I add that additional condition it gives me this error.
    ORA-00907: missing right parenthesis.
    Is there any way to get around this problem. Does SQL has other than SUBSTR function which can limit the character length.
    Appreciate it.

    The other alternative I thought about was to do this first
    EXECUTE IMMEDIATE 'SELECT pml.'||con_fields.field||'
    FROM table_name pml
    WHERE pml.grp_id = '||los_concats.grp_id||'
    AND pml.row_id = '||los_concats.row_id||'
    AND pml.loser_flg = ''Y''
    ' INTO v_concat_field;
    write into the variable v_concat_field and then use it into the previous script.
    But on this I get SQL Command not properly terminated, I don't get it Why?
    Donald I tried with your suggested script. It works fine with one of the conditions eliminated. I don't understand what the error trying to say?
    Thanks

  • Preparing Dynamic SQL statement for inserting in Pro*C

    Hi Friends,
    From quite some time i am struggling writing Dynamic SQL statement for dynamic insert and update in Pro*C.
    Can somebody go through my code and suggest me the rigth way of doing.
    Right now it throws an error saying " Error while updating ORA-00904: invalid column name "
    Please help me.
    Girish.
    int main()
    EXEC SQL BEGIN DECLARE SECTION;
    char *uid ="scott/tiger";
    static char sqlstmt[129];
    struct /* DEPT record */
    int dept_num;
    char dept_name[15];
    char location[14];
    } dept_rec;
    EXEC SQL END DECLARE SECTION;
    EXEC SQL WHENEVER SQLERROR DO sql_error();
    EXEC SQL CONNECT :uid;
    dept_rec.dept_num = 50;
    strcpy(dept_rec.dept_name,"ADMIN");
    strcpy(dept_rec.location,"IN");
    strcpy(sqlstmt,"UPDATE dept set DNAME = dept_rec.dept_name where DEPTNO = dept_rec.dept_num");
    EXEC SQL EXECUTE IMMEDIATE:sqlstmt;
    EXEC SQL COMMIT;
    exit(0);
    void sql_error()
    printf("\nError while updating %s",sqlca.sqlerrm.sqlerrmc);
    EXEC SQL ROLLBACK;
    }

    A bit rusty here but this is how I see it.
    Think of it this way ..
    all Oracle is going to see is:
    UPDATE dept set DNAME = dept_rec.dept_name where DEPTNO = dept_rec.dept_num
    Its NOT going to know what dept_rec.dept_name is or dept_rec.dept_num is ..
    it doesnt go back and fill in those values.
    You need something like
    strcpy(sqlstmt,"UPDATE dept set DNAME = \"");
    strcat(sqlstmt,dept_rec.dept_name);
    strcat(sqlstmt,"\" where DEPTNO = ");
    strcat(sqlstmt,dept_rec.dept_num);
    printf(sqlsmt); # Just to be sure the update statement look right during testing.

  • Concatenate problem for Dynamic SQL statements

    Hi Experts ,
    I am building Dynamic SQL statements depending on the values which the user enters into the select option parameters .This dynamic query is passed to cl_sql_connection object for querying from another databasse
    So i wrote dynamic values for one select option spointof for the database field ppointofdelivery.
    loop at spointof.
    CONCATENATE ' pointofdelivery between ''' spointof-low''''
    ' AND ''' spointof-high''''
    INTO where_clause .
    endloop.
    The whereclause has value pointofdelivery between '123' and '124'.(if the user has entered 123 and 124 as values)
    This works fine . But my problem is I have to pass the fieldnames and operator dynamically into where_clause depending on User input.
    when i am writing code like the below
    field_name = ' pointofdelivery '.
    operator = '='.
    CONCATENATE field_name operator '''spointof-low''' INTO where_clause .
    the where_clause contains value
    pointofdelivery = ' spointof-low '
    and not pointofdelivery = ' 123 ' as expected .
    Do you know why this is haapening as it is not taking the value.
    Thanks
    Arshad

    Hi,
    there are lot of function modules..available...to build a where clause based on the select-options..
    check the FM FREE_SELECTIONS_RANGE_2_WHERE
    Thanks
    Naren

  • How can I open a cursor for dynamic sql statement

    Hi,
    I'm facing issues opening a cursor for dynamic sql statement : PLS-00455: cursor 'RESULT1' cannot be used in dynamic SQL OPEN statement.
    CREATE OR REPLACE FUNCTION DEMO
    (MN_I in VARCHAR)
    return AB_OWNER.ABC_Type.NonCurTyp is
    RESULT1 AB_OWNER.ABC_Type.NonCurTyp;
    sql_stmt VARCHAR2(4000);
    BEGIN
    sql_stmt := 'SELECT * FROM AB_OWNER.DUN WHERE JZ_I in ('||mn_i||') ORDER BY app.ACC_I';
    OPEN RESULT1 FOR sql_stmt;
    END IF;
    return RESULT1;
    END DEMO;
    What changes should I make in the code so that it doesn't fail? I can't change the definition of RESULT1 cursor though.

    Gangadhar Reddy wrote:
    I used SYS REFCURSOR and was able to implement successfully.How many times did you run this successful implementation that does not use bind variables?
    Because this is what will happen when it runs a lot.
    http://download.oracle.com/docs/cd/E11882_01/server.112/e17766/e2100.htm#sthref1874
    http://forums.oracle.com/forums/search.jspa?q=%2BORA-04031%20%2Bbind&objID=c84&dateRange=all&rankBy=10001&start=30
    And you will have to regularly restart the server, or possibly slightly less invasive, flush the shared pool.
    Flushing Shared Pool regularly
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1516005546092
    >
    Ok, this is an easy one to diagnose.
    You are not using bind variables. This is terrible. Flushing the shared pool is a bad
    solution -- you are literally killing the performance on your box by not using them.
    If I was to write a book on how to build “non scalable applications in Oracle”, this
    would be the first and last chapter. This is a major cause of performance issues and a
    major inhibitor of scalability in Oracle. The way the Oracle shared pool (a very
    important shared memory data structure) operates is predicated on developers using bind
    variables. If you want to make Oracle run slowly, even grind to a total halt – just
    refuse to use them.
    >
    But, please feel free to go ahead with this successful implementation.
    I just hope anyone else who reads this doesn't make the same mistake.

  • Execute Dynamic SQL statement using procedure builder

    i want to execute a dynamic SQL statment using procedure builder not using forms
    because my statement depending on a variable table name
    i know that i can do that from forms using
    FORMS_DDL('SQL_STAT');
    but i wanna to use the procedure builder
    which function i should use and how?
    please explain in example if you don't mind.
    thanks

    Hi,
    You can very well use DBMS_SQL Package supplied by Oracle for doing this.
    Search for DBMS_SQL in OTN. You will get all info regarding this.
    Regards.
    <BLOCKQUOTE><font size="1" face="Verdana, Arial, Helvetica">quote:</font><HR>Originally posted by itslul:
    i want to execute a dynamic SQL statment using procedure builder not using forms
    because my statement depending on a variable table name
    i know that i can do that from forms using
    FORMS_DDL('SQL_STAT');
    but i wanna to use the procedure builder
    which function i should use and how?
    please explain in example if you don't mind.
    thanks<HR></BLOCKQUOTE>
    null

  • Dynamic SQL statements

    Hi
    Here is an interesting question for all. My application has to support 5 markets. For that I created a report based on querying a view. That report is based on some search criteria which comes through a form. Right now the report is perfectly working as I have queried it as
    select * from portland.rsu_inventory where ne = :ne_no
    But we have some more markets apart from PORTLAND. For that we want to use the same application. So we have to be able to pass the market name dynamically. I am able to capture the market name in the search croteria form. But how can I send the market name to the Report SQL statement like
    select * from &#0124; &#0124;MarketName&#0124; &#0124;.rsu_inventory where ne = :ne_no
    Here the "MarketName" should be the market name that I would dynamically pass.
    How can I acieve this. Thanks for any kind of suggession.
    venu

    According to the metalink, the new version of OracleAs Portal is no longer support the query statement passing to this wwv_render_report.show procedure but however you can pass the cursor handle to this procedure instead. Here is the sample code to call this procedure:
    declare
    v_qry_stmt varchar2(32767) ;
    v_cur_hdl int;
    begin
    v_cur_hdl := dbms_sql.open_cursor; -- open cursor
    v_qry_stmt := '<your query>';
    --Example query:
    --v_qry_stmt := 'select empno,ename from scott.emp';
    dbms_sql.parse(v_cur_hdl, v_qry_stmt, dbms_sql.native);
    PORTAL30.wwv_render_report.show(p_table_border=>'1',
    p_heading_bgcolor=>'#FFFFF0',
    p_heading_font_face=>'Arial',
    p_heading_font_size=>'13',
    p_table_bgcolor=>'#FFFFFF',
    p_font_face=>'Arial',
    p_font_size=>'10',
    p_query=>to_char(v_cur_hdl),
    p_col_headings=>PORTAL30.wwv_standard_util.string_to_table2('Employee Number:Employee Name')
    end;
    Thanks
    -Krishnamurthy

  • Dynamic SQL and Oracle stored procedures

    Does anybody has any experience with invoking an Oracle stored procedures
    with output parameters, using dynamic SQL from Forte?
    Thanks,
    Dimitar

    I would be interested. We are currently using a homegrown DataMapper architecture with the Microsoft OracleClient. I would like to move to ODP.Net once a production version supporting ADO.Net 2.0 is available. After that, I would then like to look at using an off the shelf persistence framework such as EntitySpaces, NHibernate or IdeaBlade's DevForce.

  • Comparintg times  in a dynamic sql statement

    I am working on a coversion procedure from one database to another. I have a move procedure that calls functions and the like .
    I am trying to use dynamic sql and my where clause is giving me errors. What am I missing here ? TIA....
    DEFINE DATECUTOFF ='11-JAN-05' of type date
    DES_DATE is a date column in the 2nd database .... type date
    I am building strings to do a create table from the 2nd database ...
    Testwhere := q'[where to_char("des_date", 'DD-MM-YY') < '01-JAN-05]'; === works but I want to pass in date variable
    Teststring := 'Create table '|| table_name || ' as select * from '|| second_table||'@'Linkname
    execute immediate teststring || ''|| testwhere;
    Testwhere := q'[where to_char("des_date", 'DD-MM_YY') <  to_char(DATECUTOFF, 'DD-MON-YY')]; gives me errors like invalid number, or invalid type depending on where the quotes are or how I define DATECUTOFF
    Any ideas of what I am doing wrong in comparing the two dates ?
    Thanks.

    Sorry if I confused anyone ... we're working a duo effort here and get confused ourselves. Here's a summary of the effort.
    We're on 11G Linux.
    We're writing scripts, procedures and functions that will help us transition from a remote database (Ingres) to oracle. We plan to do this for many dbs, so we are using variables for the table names, links, etc ....
    The Where clase that we are developing is pretty
    complex, so our initial attempts to build it is
    to make it into two sections as a "literal" , join them and do a execute immediate. A date fields seem to be the issue...
    Our main procedure calls a datamove function to do the select from the remote data base....
    DATECUTOFF is date;
    TESTWHERE is varchar2(600);
    TESTSTRING varchar2(600);
    TestString := 'Create table '|| table_name_temp|| as select * from '||remote_table_name||'@'Linkname;
    TestWhere :=q'[ Where ||des_date < 'DATECUTOFF'];
    execute immediate Teststring || '' ||Testwhere;
    Can I do this in dynamic plsql ? the des_date is the column from the remote database. DATACUTOFF comes from the main procedure passed in.
    I do a DBMS_OUTPUT.Put_Line{teststring);
    DBMS_OUPUT.Put_Line(testwhere);
    and get the following on my screen
    Create Table AC_KEY_TEMP as select * from ACK_KEY2@DBLINK2
    where "des_date" = 11-Jan-05
    DECLARE
    Error at line 1;
    ORA-00904 "JAN" invalid identfier
    ORA- 06512 at datamove.datamove, line 146
    ORA-06512 at line 49, which is the line for
    the TestWHERE string.
    so in the procedure, if DBMS_OUTPUT is correct, the execute immediate is operating on the where clause and it
    thinks the JAN field is incorrect. I have put single quotes around it as well ...

  • Passing plsql parm to a sql statement in the procedure  database link name

    Would like to pass a parm that is the database link name to a stored procedure.  I defined this as below. var1 is the name of the db link that I would like to pass
    create or replace procedure   proc1  (var1 in varchar2) as
    cursor c1 is
    select num,name,city from emp@var1;
    However, this is getting a plsql error in the above code   as bad bind variable, db link name expected.
    Is there a method to pass a variable within a stored proc into a SQL statement that has a cursor ..
    thanks

    Hi,
    Database links have to be hard-coded.  If you really need to specify the database link at run-time, then you need Dyanmic SQL.
    Why do you need to do this?   How many databases are involved?  Do you have new database links all the time?  The more you can say about your business requirements, the more helpful we can be.
    Are there only a couple of possible database links?  If so,  you might consider hard-coding each of them, and branching to the appropriate one in your code.
    is the real variable here the environment (Development, Test, Production) that you're in?  For example, do you need to use one database link in Development, a different one in Test, and a third in Production, but you don't want to change the code when you move from one environment to another?  If so, you can try conditional comilation.

  • Dynamic SQL Statement with table name

    Dear all
    i like to have a SQL statement with a dynamic tablename. Is this possible? If yes, how?
    should be something like "select * from <mytablename>"
    Thank you
    Herbert

    Yes this is possible. use the below reference code for this.
    data: g_tablename type w_tabname,
            gv_dref TYPE REF TO data.
    FIELD-SYMBOLS: <g_itab> TYPE STANDARD TABLE.
    gv_tabname = p_tablename (take table name form selection screen or as per ur requirement)
    CREATE DATA gv_dref TYPE TABLE OF (g_tabname).
    ASSIGN gv_dref->* TO <g_itab>.
    now use the below select query to fetch the data
      SELECT * FROM (gv_tabname) INTO TABLE <g_itab>.
    Hope this will help

  • XmlAgg Order By in SQL Statement vs Stored Procedure - 9.2.0.3.0

    Hi All,
    I'm having a problem with the XMLAgg function's ORDER BY clause after upgrading to 9.2.0.3.0.
    I'm finding that I can succesfully execute a SQL statement with the XMLAgg ORDER BY clause, but cannot compile a stored procedure using ORDER BY. Below are two examples executing against the SCOTT Schema. They use the same code, except one is contained in a procedure.
    I'm running 9.2.0.3.0 on Windows XP Pro, SP1
    Plain SQL Statement (executes correctly):
    SELECT
    XMLElement("test",
    XMLAgg(
    XMLElement("element",
    XMLAttributes(Scott.Emp.Ename as "ename", Scott.Emp.Empno as "enum")
    ) --xmlElement element
    ORDER BY Scott.Emp.Ename desc
    ) --XmlAgg
    ).getClobVal() --xmlElement test
    as TestXML
    from Scott.Emp;
    Stored Procedure:
    create or replace procedure zorder(TestXML OUT clob) is
    begin
    SELECT
    XMLElement("test",
    XMLAgg(
    XMLElement("element",
    XMLAttributes(Scott.Emp.Ename as "ename", Scott.Emp.Empno as "enum")
    ) --xmlElement element
    ORDER BY Scott.Emp.Ename desc
    ) --XmlAgg
    ).getClobVal() --xmlElement test
    into TestXML
    from Scott.Emp;
    end zorder;
    I get the following errors when attempting to compile the stored procedure:
    7 PLS-00306: wrong number of types or arguments in call to 'XMLAGG'
    7 PL/SQL: ORA-00904: "XMLAGG": invalid identifier
    5 PL/SQL: SQL Statement ignored
    Does anybody know why this code executes correctly in a SQL statement, but fails in a procedure? Is the Order By clause not available in a procedure? I need to get this functionality working in the procedure.
    Thanks,
    Brian

    A good simple workaround (that doesn't require runtime parsing) is to simply sub-query:
    SELECT
    XMLElement("test",
        XMLAgg(
            XMLElement(
                "element",
                XMLAttributes(Scott.Emp.Ename as "ename", Scott.Emp.Empno as "enum")
            ) --xmlElement element
        ) --XmlAgg
    ).getClobVal() --xmlElement test
    into TestXML
    from (
        SELECT Ename,Empno
        FROM Scott.Emp
        ORDER BY Scott.Emp.Ename desc

  • Dynamic Sql  no execute inside procedure

    Hi
    There are a new table, I give permission for select, update, inser and delete, when I executed query select work fine, but when This query is executed inside procedure with dynamic sql return error: ORA-01031 Insufficient Prvileges
    I try to test out procedure and work fine , see below
    declare
      CCURSOR SYS_REFCURSOR;
      RCURSOR TRITON.TTDSLS992901%ROWTYPE;
      V_SQL  VARCHAR2(2000);
    begin
       V_SQL :='SELECT * FROM TRITON.TTDSLS992'|| '901' || CHR(10);
       V_SQL := V_SQL || ' WHERE  T$CONO$O = 410705'|| CHR(10);
       V_SQL := V_SQL || ' AND    T$PONO$O = 10'|| CHR(10);
       V_SQL := V_SQL || ' AND    T$COND$O = 0'|| CHR(10);
       V_SQL := V_SQL ||'AND    T$ETPA$O = 1 '|| CHR(10);
       V_SQL := V_SQL || ' AND    ROWNUM   = 1'|| CHR(10);
       V_SQL := V_SQL || ' ORDER BY T$CONO$O, T$PONO$O, T$COND$O DESC';
    OPEN CCURSOR FOR V_SQL;
      FETCH CCURSOR INTO RCURSOR;
      IF CCURSOR%FOUND THEN
         NULL;
      ELSE
         NULL;  
      END IF;
      CLOSE CCURSOR;   
    end;the Code 901 is not constant, change when Company change
    Why return error permission inside procedure ?

    Hardcode the value to '901' & check TRITON.TTDSLS992901 has execute permission to schema where you want to call this
    TRITON.TTDSLS992'|| '901' ~Lokanath

Maybe you are looking for

  • Installed New Hard Drive and moved iPhoto library manually to new HD

    I dragged my old iphoto library to new hd but when i opened it up i have a ton of duplicate photos and events dont seem to be in order?  Any help with restoring iphoto events to their old self is greatly appreciated!

  • Mail and Notes problems in Mavericks

    I've just installed Mavericks and I'm instantly having problems with Mail and Notes. To wit: 1) Prior to the upgrade, I had dozens of messages flagged. Now, almost no messages show up as flagged. 2) Some Smart Mailboxes now only display only a handfu

  • How to tell if my netbook has gigabit Ethernet (and/or can use it)

    I have owned an Asus Eee 701SD (the 8GB version) since 2009, and installed Arch on it last summer (a great move :-) ). The other day, I came across a page on the FreeBSD wiki, which suggested that certain 700-series Eee's have a gigabit Ethernet inte

  • Clear Command Line

    Hi all would like to know if there is anyway i can clear the stuff already present in the command line promt using java. Thanks

  • Folio Builder is missing from indesign cs6 panel

    Hi, I have Indeisgn CS6. I need to access my Folio Builder, however after updating the system my folio builder has disappeared completely from the drop down 'Windows' tool. Any idea how to get this back?