Dynamic SQL and IN CLAUSE from Pro C code

Hi Guys,
Tyring to embed sql in Pro C. Here I don't know in hand how many items will be there in the IN Clause of my dynamic sql. Tried this with a loop and then adding actual values to the stement and then executing it. This worked but as this hard coding makes it literal sql and hence hampers performance. Can any one help me with how to put bind variables where we don't know how many of them will be there in a dynamic sql.
Thanks,

Dynamic SQL supports user defined types, try passing a collection and using TABLE(CAST(collection)) in the SQL statement.
In the current approach (creating IN clause at runtime) keep in mind that in a IN clause you can put a maximum of 255 elements...
Max

Similar Messages

  • Dynamic SQL and Bulk Bind... Interesting Problem !!!

    Hi Forum !!
    I've got a very interesting problem involving Dynamic SQL and Bulk Bind. I really Hope you guys have some suggestions for me...
    Table A contains a column named TX_FORMULA. There are many strings holding expressions like '.3 * 2 + 1.5' or '(3.4 + 2) / .3', all well formed numeric formulas. I want to calculate each formula, finding the number obtained as a result of each calculation.
    I wrote something like this:
    DECLARE
    TYPE T_FormulasNum IS TABLE OF A.TX_FORMULA%TYPE
    INDEX BY BINARY_INTEGER;
    TYPE T_MontoIndicador IS TABLE OF A.MT_NUMBER%TYPE
    INDEX BY BINARY_INTEGER;
    V_FormulasNum T_FormulasNum;
    V_MontoIndicador T_MontoIndicador;
    BEGIN
    SELECT DISTINCT CD_INDICADOR,
    TX_FORMULA_NUMERICA
    BULK COLLECT INTO V_CodIndicador, V_FormulasNum
    FROM A;
    FORALL i IN V_FormulasNum.FIRST..V_FormulasNum.LAST
    EXECUTE IMMEDIATE
    'BEGIN
    :1 := TO_NUMBER(:2);
    END;'
    USING V_FormulasNum(i) RETURNING INTO V_MontoIndicador;
    END;
    But I'm getting the following messages:
    ORA-06550: line 22, column 43:
    PLS-00597: expression 'V_MONTOINDICADOR' in the INTO list is of wrong type
    ORA-06550: line 18, column 5:
    PL/SQL: Statement ignored
    ORA-06550: line 18, column 5:
    PLS-00435: DML statement without BULK In-BIND cannot be used inside FORALL
    Any Idea to solve this problem ?
    Thanks in Advance !!

    Hallo,
    many many errors...
    1. You can use FORALL only in DML operators, in your case you must use simple FOR LOOP.
    2. You can use bind variables only in DML- Statements. In other statements you have to use literals (hard parsing).
    3. RETURNING INTO - Clause in appropriate , use instead of OUT variable.
    4. Remark: FOR I IN FIRST..LAST is not fully correct: if you haven't results, you get EXCEPTION NO_DATA_FOUND. Use Instead of 1..tab.count
    This code works.
    DECLARE
    TYPE T_FormulasNum IS TABLE OF VARCHAR2(255)
    INDEX BY BINARY_INTEGER;
    TYPE T_MontoIndicador IS TABLE OF NUMBER
    INDEX BY BINARY_INTEGER;
    V_FormulasNum T_FormulasNum;
    V_MontoIndicador T_MontoIndicador;
    BEGIN
    SELECT DISTINCT CD_INDICATOR,
    TX_FORMULA_NUMERICA
    BULK COLLECT INTO V_MontoIndicador, V_FormulasNum
    FROM A;
    FOR i IN 1..V_FormulasNum.count
    LOOP
    EXECUTE IMMEDIATE
    'BEGIN
    :v_motto := TO_NUMBER('||v_formulasnum(i)||');
    END;'
    USING OUT V_MontoIndicador(i);
    dbms_output.put_line(v_montoindicador(i));
    END LOOP;
    END;You have to read more about bulk- binding and dynamic sql.
    HTH
    Regards
    Dmytro
    Test table
    a
    (cd_indicator number,
    tx_formula_numerica VARCHAR2(255))
    CD_INDICATOR TX_FORMULA_NUMERICA
    2 (5+5)*2
    1 2*3*4
    Message was edited by:
    Dmytro Dekhtyaryuk

  • Dynamic SQL and Sub Query

    I want need to use dynamic SQL, and include a subquery in the where clause.  However, I am getting a syntax error.
    I have code that looks like this.
        SELECT (p_v_sqlobj_select)
            INTO CORRESPONDING FIELDS OF TABLE <matrix>
          FROM (p_v_sqlobj_from)
          WHERE (p_v_sqlobj_where).
    and I pass it the following bold-faced SQL where clause (please ignore whether the statement makes sense and is the best way to do it - this is just to illustrate).   However, it returns an error.
    select tcode from tstc where tcode in <b>( select min( tcode ) as min from tstc )</b>
    Am I correct in concluding that I cannot pass complex statements, or have I just missed something?
    Thanks for any help.

    Hi,
    Please try with order by clause in select statement and also use descending
          select * from (p_table)
                   into corresponding fields of table <ptab>
                  up to p_rows rows
                  order by <fieldname> descending.
    aRs

  • Dynamic SQL and Data with Single Quotes in it.

    Hi There,
    I have a problem in that I am using dynamic SQL and it happens that one of the columns does contain single quotes (') in it as part of the data. This causes the resultant dynamic SQL to get confused as the single quote that is part of the data is taken to mean end of sting, when in fact its part of the data. This leaves out a dangling single quote that was meant to enclose the string. Here is my dynamic SQL and the result of the parsed SQL that I have captured:
    ****Dynamic SQL*****
    l_sql:='select NOTE_TEMPLATE_ID '||
    'FROM TMP_NOTE_TEMPLATE_VALUES '||
    'where TRIM(LEGACY_NOTE_CODE)='''||trim(fp_note_code)||''' '||
    'and TRIM(DISPLAY_VALUE)='''||trim(fp_note_text)||''' ';
    execute immediate l_sql INTO l_note_template_id;
    Because the column DISPLAY_VALUE contains data with single quotes, the resultant SQL is:
    ******PARSED SQL************
    select NOTE_TEMPLATE_ID
    FROM TMP_NOTE_TEMPLATE_VALUES
    where TRIM(LEGACY_NOTE_CODE)='INQ' and TRIM(DISPLAY_VALUE)='Cont'd'
    And the problem lies with the single quote between teh characters t and d in the data field for DISPLAY_ITEM. How can I handle this?
    Many thanks,

    I have been reliably informed that if one doesn't enclose char/varchar2 data items in quotes, the right indices may not be usedI am into oracle for past 4 years and for the first time i am hearing this.
    Your reliable source is just wrong. Bind variables are variables that store your value and which are used in SQL. They are the proper way to use values in your SQL. By default all variables in PL/SQL is bind variable.
    When you can do some thing in just straight SQL just do it. Dynamic SQL does not make any sense to me here.
    Thanks,
    Karthick.

  • Best way to spool DYNAMIC SQL query to file from PL/SQL

    Best way to spool DYNAMIC SQL query to file from PL/SQL [Package], not SqlPlus
    I'm looking for suggestions on how to create an output file (fixed width and comma delimited) from a SELECT that is dynamically built. Basically, I've got some tables that are used to define the SELECT and to describe the output format. For instance, one table has the SELECT while another is used to defined the column "formats" (e.g., Column Order, Justification, FormatMask, Default value, min length, ...). The user has an app that they can use to customize the output...which leaving the gathering of the data untouched. I'm trying to keep this formatting and/or default logic out of the actual query. This lead me into a problem.
    Example query :
    SELECT CONTRACT_ID,PV_ID,START_DATE
    FROM CONTRACT
    WHERE CONTRACT_ID = <<value>>Customization Table:
    CONTRACT_ID : 2,Numeric,Right
    PV_ID : 1,Numeric,Mask(0000)
    START_DATE : 3,Date,Mask(mm/dd/yyyy)The first value is the kicker (ColumnOrder) as well as the fact that the number of columns is dynamic. Technically, if I could use SqlPlus...then I could just use SPOOL. However, I'm not.
    So basically, I'm trying to build a generic routine that can take a SQL string execute the SELECT and map the output using data from another table to a file.
    Any suggestions?
    Thanks,
    Jason

    You could build the select statement within PL/SQL and open it using a cursor variable. You could write it to a file using the package 'UTL_FILE'. If you want to display the output using SQL*Plus, you could have an out parameter as a ref cursor.

  • Just upgraded to MacBook Pro running 10.8.4.  Want to convert old movie files to put in Itunes.  Can't upgrade QT player preinstalled, so downloaded QT Player 7 and purchased QTPlayer 7 Pro registration code.  Can not get it to upgrade.  Called Apple 2x.

    Just upgraded to MacBook Pro running 10.8.4.  Want to convert old movie files to put in Itunes.  Can't upgrade QT player preinstalled, so downloaded QT Player 7 and purchased QTPlayer 7 Pro registration code.  Can not get it to upgrade.  Called Apple 2x.  If you have a fix, you can email me direct at [email protected]

    Want to convert old movie files to put in Itunes.
    What does "old movies" mean to you? File type, audio and/or video compression format(s)?
    Can't upgrade QT player preinstalled, so downloaded QT Player 7 and purchased QTPlayer 7 Pro registration code.  Can not get it to upgrade.
    Did you follow the instructions found here?
    If you have a fix, you can email me direct at [email protected]
    To which fix do you refer? Activatng QT 7 Pro or converting the files? Even with QT 7 Pro activated you may need to modify your QT codec component configuration depending on the file type and compression formats used to encode your "old movies." There may be many different problems here with each having one or more "fixes." Please try to be more specific regarding your questions. Converting a muxed VOB MPEG2/AC3 file would be very different different from converting an AVI DivX5/MP3 file depending on which application you are attempting to use.

  • Dynamic SQL with cursor variables in pro*c

    Please, what I need to do in order to be able
    to do something like this:
    EXEC SQL DECLARE :c CURSOR FOR :s;
    In other words: I want to use variables
    in cursor names.
    Is it possible ? How ?
    Thank you.

    OK. Here is an example of a Dynamic SQL #4 program I wrote several years ago (It's still running in production). It is currently running on a Sun E10K with Oracle 8.1.5. This code is JUST the pro*c part of a program which uses IBM MQ Series. MQ passes this program a Select SQL statement (as well as other parameters) as an argument. The Pro*c code allocates the structures, parses, and fetches, and executes the statement. I realize that this will not be easy to read. There are SOME comments in the code. However, I realize that to read anyone elses code is a chore. When you add Dynamic #4 to the list, it becomes much more complicated. Anyway, you'll probably need to copy and paste the code to a text file. It will be easier to read.
    ==========================================
    Code
    ==========================================
    | Program: mqsql.pc |
    | Creator: Jim Wartnick |
    | Purpose: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX |
    | XXXXXXXXXXX |
    | Date: 01/03/1997 |
    | Modifications: |
    #include"mqsql.h"
    #define DEBUG
    #ifdef DEBUG
    FILE *fp=stdout;
    #endif
    int
    disconnect_db() {
    char msg[256], oraclmsg[256];
    char buf[MAX_STRING_LENGTH+4];
    int buf_len = 0, msg_len = 0;
    EXEC SQL
    COMMIT WORK RELEASE;
    #ifdef DEBUG
    fprintf(fp, " --> Disconnecting from database. RC: %d.\n", sqlca.sqlcode);
    fflush(fp);
    #endif
    if (sqlca.sqlcode != 0) {
    buf_len = sizeof(oraclmsg)-1;
    sqlglm(oraclmsg, &buf_len, &msg_len);
    oraclmsg[msg_len] = '\0';
    error("disconnect_db()", "disconnect", sqlca.sqlcode, oraclmsg);
    return(FAILURE);
    return(SUCCESS);
    int
    connect_db() {
    char msg[256], oraclmsg[256];
    char buf[MAX_STRING_LENGTH+4];
    int buf_len = 0, msg_len = 0;
    char user[4];
    strcpy(user, "/");
    EXEC SQL
    CONNECT :user;
    #ifdef DEBUG
    fprintf(fp, " --> Connecting to database. RC is %d\n", sqlca.sqlcode);
    fflush(fp);
    #endif
    if (sqlca.sqlcode != 0) {
    buf_len = sizeof(oraclmsg)-1;
    sqlglm(oraclmsg, &buf_len, &msg_len);
    oraclmsg[msg_len] = '\0';
    sprintf(Results, "%9d", sqlca.sqlcode);
    error("connect_db()", "connect", sqlca.sqlcode, oraclmsg);
    return(FAILURE);
    return(SUCCESS);
    int
    allocate_sqlda() {
    | Initialize the SQLDA structure. |
    | We only need the select descriptor |
    | because we do not have any bind |
    | variables. |
    if ((Select_da = sqlald(
    MAX_COLUMN_COUNT,
    MAX_COLUMN_STRING_LENGTH,
    MAX_INDICATOR_VARS
    )) == (SQLDA *) 0) {
    #ifdef DEBUG
    fprintf(fp, " Memory allocation for Select Descriptor failed.\n");
    fflush(fp);
    #endif
    strcpy(Results, "000000001");
    error("allocate_sqlda()", "create SQLDA", 0, "Memory Error");
    return(FAILURE);
    #ifdef DEBUG
    fprintf(fp, " Memory allocation for Select Descriptor succeeded.\n");
    fflush(fp);
    #endif
    Select_da->N = MAX_COLUMN_COUNT;
    return(SUCCESS);
    int
    prepare_sql() {
    char msg[256], oraclmsg[256];
    int buf_len = 0, msg_len = 0;
    | Prepare the Sql statement. |
    EXEC SQL
    PREPARE sql_stmt
    FROM :Sql;
    #ifdef DEBUG
    fprintf(fp, " Prepared SQL: %s. RC: %d.\n", Sql, sqlca.sqlcode);
    fflush(fp);
    #endif
    if (sqlca.sqlcode != 0) {
    buf_len = sizeof(oraclmsg)-1;
    sqlglm(oraclmsg, &buf_len, &msg_len);
    oraclmsg[msg_len] = '\0';
    sprintf(Results, "%9d", sqlca.sqlcode);
    error("prepare_sql()", "Parse", sqlca.sqlcode, oraclmsg);
    return(FAILURE);
    return(SUCCESS);
    int
    declare_cursor() {
    char msg[256], oraclmsg[256];
    int buf_len = 0, msg_len = 0;
    | Set up the cursor to loop through |
    EXEC SQL
    DECLARE sql_cursor
    CURSOR FOR sql_stmt;
    #ifdef DEBUG
    fprintf(fp, " Declared cursor. RC: %d\n", sqlca.sqlcode);
    fflush(fp);
    #endif
    if (sqlca.sqlcode != 0) {
    buf_len = sizeof( oraclmsg)-1;
    sqlglm(oraclmsg, &buf_len, &msg_len);
    oraclmsg[msg_len] = '\0';
    sprintf(Results, "%9d", sqlca.sqlcode);
    error("declare_cursor()", "declare cursor", sqlca.sqlcode, oraclmsg);
    return(FAILURE);
    return(SUCCESS);
    int
    open_cursor() {
    char msg[256], oraclmsg[256];
    int buf_len = 0, msg_len = 0;
    | Open the cursor. |
    EXEC SQL
    OPEN sql_cursor;
    #ifdef DEBUG
    fprintf(fp, " Opened cursor. RC:%d\n", sqlca.sqlcode);
    fflush(fp);
    #endif
    if (sqlca.sqlcode != 0) {
    buf_len = sizeof(oraclmsg)-1;
    sqlglm(oraclmsg, &buf_len, &msg_len);
    oraclmsg[msg_len] = '\0';
    sprintf(Results, "%9d", sqlca.sqlcode);
    error("open_cursor()", "open cursor", sqlca.sqlcode, oraclmsg);
    return(FAILURE);
    return(SUCCESS);
    int
    describe_select_list() {
    char msg[256], oraclmsg[256];
    int buf_len = 0, msg_len = 0;
    | Get description of columns |
    EXEC SQL
    DESCRIBE SELECT LIST FOR sql_stmt
    INTO Select_da;
    #ifdef DEBUG
    fprintf(fp, " Described columns. RC %d\n", sqlca.sqlcode);
    fflush(fp);
    #endif
    if (sqlca.sqlcode != 0) {
    buf_len = sizeof(oraclmsg)-1;
    sqlglm(oraclmsg, &buf_len, &msg_len);
    oraclmsg[msg_len] = '\0';
    sprintf(Results, "%9d", sqlca.sqlcode);
    error("describe_select_list()", "describe select list", sqlca.sqlcode, oraclmsg);
    return(FAILURE);
    return(SUCCESS);
    int
    setup_sqlda() {
    char buf[MAX_STRING_LENGTH+4];
    int done = FALSE, nullok = 0, i = 0;
    #ifdef DEBUG
    fprintf(fp, " --> Setting up SQLDA.\n");
    fflush(fp);
    #endif
    if (allocate_sqlda() == FAILURE)
    return(FAILURE);
    if (prepare_sql() == FAILURE)
    return(FAILURE);
    if (declare_cursor() == FAILURE)
    return(FAILURE);
    if (open_cursor() == FAILURE)
    return(FAILURE);
    if (describe_select_list() == FAILURE)
    return(FAILURE);
    | Too many columns in select list. |
    if (Select_da->F < 0) {
    strcpy(Results, "000000001");
    error("setup_sqlda()", "check select list count", 0, "Too many values in select list");
    return(FAILURE);
    | Set the number of columns to the actual |
    | number of columns. |
    Select_da->N = Select_da->F;
    | We are going to convert all fields to a string. |
    for (i == 0; i < Select_da->F; i++) {
    sqlnul(&(Select_da->T), &(Select_da->T[i]), &nullok);
    Select_da->T[i] = EXT_STRING;
    Select_da->L[i] = MAX_STRING_LENGTH;
    | Allocate the result area to be as big as |
    | MAX_STRING_LENGTH. |
    if ((Select_da->V[i] = malloc(Select_da->L[i])) == NULL) {
    #ifdef DEBUG
    fprintf(fp, " Allocation of column values failed.\n");
    fflush(fp);
    #endif
    strcpy(Results, "000000001");
    error("setup_sqlda()", "allocate column values", 0, "Memory Error");
    return(FAILURE);
    if ((Select_da->I[i] = (short *) malloc(sizeof(short))) == NULL) {
    #ifdef DEBUG
    fprintf(fp, " Allocation of idicator values failed.\n");
    fflush(fp);
    #endif
    strcpy(Results, "000000001");
    error("setup_sqlda()", "allocate indicator values", 0, "Memory Error");
    return(FAILURE);
    #ifdef DEBUG
    fprintf(fp, " Allocation of memory for values succeeded.\n");
    fflush(fp);
    #endif
    return(SUCCESS);
    | add_eom adds the end of message |
    | delimiter (an aditional comma). |
    int
    add_eom() {
    char *result_ptr;
    if (strlen(Results) >= sizeof(Results) - 1) {
    strcpy(Results, "000000001");
    error("add_eom()", "Add eom failed. Size overflow", 0, "Memory Error");
    return(FAILURE);
    result_ptr = &Results[strlen(Results)-1];
    while (*result_ptr && (*result_ptr != ','))
    result_ptr--;
    if (*result_ptr) {
    result_ptr++;
    *(result_ptr++) = ',';
    *result_ptr = '\0';
    return(SUCCESS);
    int close_cursor() {
    char msg[256], oraclmsg[256];
    int buf_len = 0, msg_len = 0;
    | Close the cursor. |
    EXEC SQL
    CLOSE sql_cursor;
    #ifdef DEBUG
    fprintf(fp, " Closing cursor. RC: %d\n", sqlca.sqlcode);
    fflush(fp);
    #endif
    if (sqlca.sqlcode != 0) {
    buf_len = sizeof(oraclmsg)-1;
    sqlglm(oraclmsg, &buf_len, &msg_len);
    oraclmsg[msg_len] = '\0';
    error("generate_sql()", "close cursor", sqlca.sqlcode, oraclmsg);
    return(FAILURE);
    return(SUCCESS);
    int
    fetch() {
    char msg[256], oraclmsg[256];
    char buf[MAX_STRING_LENGTH+4];
    int buf_len = 0, msg_len = 0;
    EXEC SQL
    FETCH sql_cursor
    USING DESCRIPTOR Select_da;
    #ifdef DEBUG
    fprintf(fp, " --> Fetching rows. RC %d\n", sqlca.sqlcode);
    fflush(fp);
    #endif
    if (sqlca.sqlcode != 0) {
    if (sqlca.sqlcode != NODATAFOUND) {
    buf_len = sizeof(oraclmsg)-1;
    sqlglm(oraclmsg, &buf_len, &msg_len);
    oraclmsg[msg_len] = '\0';
    error("fetch()", "Error fetching row.", sqlca.sqlcode, oraclmsg);
    return(sqlca.sqlcode);
    return(NODATAFOUND);
    return(SUCCESS);
    | Free up any memory structures. |
    void
    free_memory() {
    int i = 0;
    for (i = 0; i < Select_da->F; i++) {
    free(Select_da->V[i]);
    free(Select_da->I[i]);
    | generate_sql() uses the message we received from the queue |
    | (a SQL statement) to query the database. We have to use |
    | dynamic Sql Version 4 for this type of Sql. The number of |
    | columns we are selecting is unknown. This means we can't |
    | use the INTO clause. |
    int
    generate_sql() {
    char buf[MAX_STRING_LENGTH+4];
    int rc = SUCCESS, done = FALSE, nullok = 0, i = 0;
    #ifdef DEBUG
    if ((fp = fopen(SQLLOG, "a")) == NULL)
    fp = stderr;
    #endif
    | Connect to the database |
    if (connect_db() == FAILURE)
    return(FAILURE);
    if (setup_sqlda() == FAILURE)
    return(FAILURE);
    | Place the answer in a comma delimited buffer. |
    memset(Results, NULL, sizeof(Results));
    done = FALSE;
    while (!done) {
    rc = fetch();
    if (rc != SUCCESS) {
    if (Results[0] == '\0')
    sprintf(Results, "%9d,", rc);
    done = TRUE;
    else {
    | Put return code of success in first. |
    if (Results[0] == '\0')
    strcpy(Results, "000000000,");
    for (i = 0; i < Select_da->F; i++) {
    Select_da->V[i][Select_da->L[i]] = '\0';
    | Check to see if the value is null. |
    if (*Select_da->I[i] < 0)
    strcpy(buf, " ,");
    else
    sprintf(buf, "%s,", Select_da->V[i]);
    if (strlen(Results) + strlen(buf) > sizeof(Results)) {
    strcpy(Results, "000000001");
    error("generate_sql()", "String concat failed. Size overflow", 0, "Memory Error");
    return(FAILURE);
    strcat(Results, buf);
    #ifdef DEBUG
    fprintf(fp, " --> Results %s\n", Results);
    fflush(fp);
    #endif
    | Close the cursor. |
    close_cursor();
    | Disconnect from the database |
    disconnect_db();
    | Remove trailing comma. |
    if (add_eom() == FAILURE)
    return(FAILURE);
    #ifdef DEBUG
    fflush(fp);
    #endif
    free_memory();
    #ifdef DEBUG
    fclose(fp);
    #endif
    null

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

  • Dynamic SQL and MERGE

    Hi all,
    I'm under 10G r1
    I want to execute a dynamic SQL with merge in it
    when I try with insert ,update it works
    but I just want to use merge if possible
    this is the code
    CREATE OR REPLACE
    PROCEDURE I_COLUMN_CDS_FIXINGS
    v_ticker VARCHAR2,
    v_date DATE,
    v_tenor VARCHAR2,
    v_bid NUMBER,
    v_ask NUMBER)
    AS
    l_column VARCHAR2(80);
    v_column_bid VARCHAR2(80);
    v_column_ask VARCHAR2(80);
    v_source VARCHAR2(60) :='CMAN@BBG';
    v_gen_order pls_integer;
    BEGIN
    SELECT 'CDS_SPREAD_'
    ||v_TENOR
    ||'_BID'
    INTO v_column_bid
    FROM dual;
    SELECT 'CDS_SPREAD_'
    ||v_TENOR
    ||'_ASK'
    INTO v_column_ask
    FROM dual;
    dbms_output.put_line(v_ticker||' '||v_column_ask||' '||v_column_bid||' '||v_bid|| ' '||v_ask||' '||v_date);
    EXECUTE immediate 'MERGE into CDS_FIXINGS C
    using ( select v_ticker,'
    ||v_column_bid
    ||','
    ||v_column_ask
    ||',trunc(v_date) info_date ,v_bid,v_ask from dual ) B
    on (C.cds_ticker=b.v_ticker and c.info_date=b.info_date)
    WHEN MATCHED THEN
    update set '||v_column_bid||'=:1,'||v_column_ask||'=:2 using v_bid,v_ask
    WHEN NOT MATCHED THEN
    INSERT
    CDS_TICKER ,
    INFO_DATE ,
    '||v_column_bid||' ,
    '||v_column_ask||' ,
    SOURCE
    VALUES (:1, :2,:3,:4,:5) ' using v_ticker,
    v_date ,
    v_bid ,
    v_ask ,
    v_source
    ---EXCEPTION
    ---when others then raise;
    end;
    when I launch hte procedure
    exec i_column_cds_fixings('TEST',trunc(sysdate-1),'8Y',4232.01,4234.02);
    I get
    ERROR at line 1:
    ORA-00933: SQL command not properly ended
    ORA-06512: at "OWNER_HISTO.I_COLUMN_CDS_FIXINGS", line 26
    ORA-06512: at line 1
    How can I deal with this
    Thanks
    babata
    I get

    Sorry
    this is formatted one
    REATE OR REPLACE PROCEDURE i_Column_cds_FixIngs
    (v_Ticker VARCHAR2,
    v_Date DATE,
    v_Tenor VARCHAR2,
    v_Bid NUMBER,
    v_Ask NUMBER)
    AS
    l_Column VARCHAR2(80);
    v_Column_Bid VARCHAR2(80);
    v_Column_Ask VARCHAR2(80);
    v_Source VARCHAR2(60) := 'CMAN@BBG';
    v_gen_Order PLS_INTEGER;
    BEGIN
    SELECT 'CDS_SPREAD_'
    ||v_Tenor
    ||'_BID'
    INTO v_Column_Bid
    FROM Dual;
    SELECT 'CDS_SPREAD_'
    ||v_Tenor
    ||'_ASK'
    INTO v_Column_Ask
    FROM Dual;
    dbms_Output.Put_Line(v_Ticker
    ||' '
    ||v_Column_Ask
    ||' '
    ||v_Column_Bid
    ||' '
    ||v_Bid
    ||' '
    ||v_Ask
    ||' '
    ||v_Date);
    EXECUTE IMMEDIATE 'MERGE into CDS_FIXINGS C
    using ( select v_ticker,'
    ||v_Column_Bid
    ||','
    ||v_Column_Ask
    ||',trunc(v_date) info_date ,v_bid,v_ask from dual ) B
    on (C.cds_ticker=b.v_ticker and c.info_date=b.info_date)
    WHEN MATCHED THEN
    update set '
    ||v_Column_Bid
    ||'=:1,'
    ||v_Column_Ask
    ||'=:2 USING v_bid,v_ask
    WHEN NOT MATCHED THEN
    INSERT
    CDS_TICKER ,
    INFO_DATE ,
    ||v_Column_Bid
    ||' ,
    ||v_Column_Ask
    ||' ,
    SOURCE
    VALUES
    :1,
    :2,
    :3,
    :4,
    :5
    USING v_Ticker,v_Date,v_Bid,v_Ask,v_Source;
    ---EXCEPTION
    ---when others then raise;
    END;
    /

  • Dynamic sql and cursors

    We are running an oracle sql procedure that uses a LOT of dynamic sql. We are using a 3rd party package (SQR) as a sort of shell to run the sql procedure. The 3rd party package passes to us an oracle error. This error says, in effect, that there are no inactive database cursors available and that the sql program is too large to process. We conclude from this that we must increase one or more of the cursor parameters in init.ora (v$parameters). Is this the correct assumption? If not, does anyone know what we can do? We'd prefer not to break up the sql procedure into smaller pieces.

    increase the parameter for open cursors.
    check, wether all cursors in your programs are closed in time, or if you are using ref cursors from front-ends (e.g. Java JDBC) that this front-ends close these ref cursors , too.
    If you want to decrease the size of procedures get rid of comments, superfluos spaces, tabs, etc.
    keep a commented version outside vor documentation purposes.
    Hope thsi helps

  • Dynamic SQL and use of aggregate functions

    Hello Forum members,
    I'm trying to create dynamic SQL in a function module and return the MAX value of a field. 
    I am passing in a parameter called CREATE_FIELD_NAME, and my SQL is
    SELECT MAX(CREATE_FIELD_NAME) INTO (CREATE_DATE) FROM (TABLE_NAME).
    I also tried:
    SELECT MAX((CREATE_FIELD_NAME)) INTO (CREATE_DATE) FROM (TABLE_NAME).
    But abap is not recognizing my variable as a variable in either case, but rather, as a field name.
    Anyone know a way around this?
    Thanks in advance,
    Jeff
    Here is my program:
    FUNCTION ZJLSTEST4.
    ""Local Interface:
    *"  IMPORTING
    *"     VALUE(TABLE_NAME) LIKE  MAKT-MAKTX
    *"     VALUE(CREATE_FIELD_NAME) LIKE  MAKT-MAKTX
    *"     VALUE(UPDATE_FIELD_NAME) LIKE  MAKT-MAKTX
    *"  EXPORTING
    *"     VALUE(MAX_DATE) LIKE  SY-DATUM
    DATA: CREATE_DATE LIKE MCHA-ERSDA VALUE '19000101',
          UPDATE_DATE LIKE MCHA-LAEDA VALUE '19000101'.
    SELECT MAX(CREATE_FIELD_NAME) INTO (CREATE_DATE) FROM (TABLE_NAME).
    ENDSELECT.
    *SELECT MAX((UPDATE_FIELD_NAME)) INTO (UPDATE_DATE) FROM (TABLE_NAME).
    *ENDSELECT.
    IF CREATE_DATE > UPDATE_DATE.
       MAX_DATE = CREATE_DATE.
    ELSE.
       MAX_DATE = UPDATE_DATE.
    ENDIF.
    IF MAX_DATE = '19000101'.
    MAX_DATE = SY-DATUM.
    ENDIF.
    ENDFUNCTION.

    Max is right, you need the spaces, as in my example.
    You might like to try this:
    data: l_CREATE_FIELD_NAME) LIKE MAKT-MAKTX,
          l_UPDATE_FIELD_NAME) LIKE MAKT-MAKTX.
    DATA: CREATE_DATE LIKE MCHA-ERSDA VALUE '19000101',
    UPDATE_DATE LIKE MCHA-LAEDA VALUE '19000101'.
    concatenate 'MAX(' create_name ')' into l_create_name separated by space.
    concatenate 'MAX(' update_name ')' into l_update_name separated by space.
    SELECT SINGLE (l_CREATE_FIELD_NAME)
    INTO CREATE_DATE FROM (table_name).
    SELECT SINGLE (l_updATE_FIELD_NAME)
    INTO updATE_DATE FROM (table_name).
    IF CREATE_DATE > UPDATE_DATE.
    MAX_DATE = CREATE_DATE.
    ELSE.
    MAX_DATE = UPDATE_DATE.
    ENDIF.
    IF MAX_DATE = '19000101'.
    MAX_DATE = SY-DATUM.
    ENDIF.
    If it still fails please post the latest abap code for us to check.

  • Dynamic SQL and PL/SQL Gateway

    This question is kind of out of curiosity...I had created a procedure that used some dynamic sql (execute immediate), and was trying to use it on pl/sql gateway. I kept getting page not found errors until I removed the execute immediate statement, and reverted to using static sql statements.
    I am just curious, is dynamic sql not supported at all with pl/sql gateway?
    Thanks
    Kevin

    > Relax damorgan, no need to be condescending. Of course I read the docs ..
    Well, you're one of the few that actually read the docs.. And one of many that lacked to state any real technical details for forum members to understand the actual problem, the actual error, and what the environment is that this is happening in.
    Remember that you came to this forum for forum members to help you. In order for us to do that, you need to help us understand
    - your problem
    - your environment
    - what you have tried
    What PL/SQL Gateway do you refer to? Thus is an old term for an old product - today in Oracle there are two "gateways" into the PL/SQL engine via HTTP. Via Apache/mod_plsql and via the internal Java servlet web engine called EPG inside Oracle.
    As for what the "Gateway" access to the PL/SQL engine via HTTP.. whether it supports EXECUTE IMMEDIATE or not is like asking if a car "supports" soft drinks or not (just because a human that may consume soft drinks acts as the driver of the car). Not sensible or relevant at all.
    mod_plsql creates an Oracle session to the database instance, and executes a PL/SQL procedure in the database. This is no different from any other client connection to Oracle. Oracle has no clue that the client is mod_plsql and not TOAD or Java or VB or PHP or Perl or whatever else.
    So how can this support or not support the EXECUTE IMMEDIATE command? Does PL/SQL support EXECUTE IMMEDIATE? Well duh...
    Why do you get a generic 404? Because the PL/SQL call made by mod_plsql failed with an unhandled exception. mod_plsql gets that exception and now what? Was a valid HTP buffer created for it to stream to the web browser? If the buffer perhaps partially completed? All that mod_plsql knows is that it asked for a HTP buffer via that PL/SQL call and it got an exception in return.
    A 404 HTTP error is the only reasonable and logical response for it to pass to the web browser in this case.
    PS. to see why mod_plsql fail, refer to the access_log and error_log of that Apache httpd server

  • Dynamic SQL and PL/SQL

    I have the following scenario:
    User Scott has two tables named USERINFO and EMP with the following description:
    desc USERINFO
    schema varchar2(30)
    desc EMP
    ename varchar2(30)
    empno number(4)
    User Blake has one table named EMP which looks like:
    desc EMP
    ename varchar2(30)
    I want to write a function which would copy the values from Scott's EMP table to Blake's EMP table but I want to get the user Blake's name from USERINFO's schema column. I figured I'd have to use dynamic SQL but am getting some errors when I execute the function. It compiles fine. Below is the code
    CREATE OR REPLACE FUNCTION CopyInfo()
    RETURN VARCHAR2 AS
    name VARCHAR22(30);
    target_schema VARCHAR2(30);
    ret_str CHAR := NULL;
    BEGIN
    SELECT schema INTO target_schema FROM version;
    SELECT ename INTO name FROM scott.emp WHERE empno = 7902;
    DECLARE
    sqlStmt VARCHAR2(1028);
    BEGIN
    sqlStmt := 'INSERT INTO ' || target_schema || '.emp VALUES( name )';
    execute SqlStmt ;
    END;
    ret_str := 't';
    RETURN ret_str;
    END CopyInfo
    When I create the function, it comes back with -
    Function created.
    when I try to execute I get an error as shown below:
    SQL>BEGIN
    2 DBMS_OUTPUT.PUT_LINE( CopyInfo());
    3 END;
    4 /
    ERROR at line 1:
    ORA-00984: column not allowed here
    ORA-06512: at "SCOTT.COPYINFO", line 13
    ORA-06512: at line 2
    Any idea, how to fix this ??? Thanks a lot....

    ---Sorry I meant userinfo not version in the code----
    I have the following scenario:
    User Scott has two tables named USERINFO and EMP with the following description:
    desc USERINFO
    schema varchar2(30)
    desc EMP
    ename varchar2(30)
    empno number(4)
    User Blake has one table named EMP which looks like:
    desc EMP
    ename varchar2(30)
    I want to write a function which would copy the values from Scott's EMP table to Blake's EMP table but I want to get the user Blake's name from USERINFO's schema column. I figured I'd have to use dynamic SQL but am getting some errors when I execute the function. It compiles fine. Below is the code
    CREATE OR REPLACE FUNCTION CopyInfo()
    RETURN VARCHAR2 AS
    name VARCHAR22(30);
    target_schema VARCHAR2(30);
    ret_str CHAR := NULL;
    BEGIN
    SELECT schema INTO target_schema FROM userinfo;
    SELECT ename INTO name FROM scott.emp WHERE empno = 7902;
    DECLARE
    sqlStmt VARCHAR2(1028);
    BEGIN
    sqlStmt := 'INSERT INTO ' || target_schema || '.emp VALUES( name )';
    execute SqlStmt ;
    END;
    ret_str := 't';
    RETURN ret_str;
    END CopyInfo
    When I create the function, it comes back with -
    Function created.
    when I try to execute I get an error as shown below:
    SQL>BEGIN
    2 DBMS_OUTPUT.PUT_LINE( CopyInfo());
    3 END;
    4 /
    ERROR at line 1:
    ORA-00984: column not allowed here
    ORA-06512: at "SCOTT.COPYINFO", line 13
    ORA-06512: at line 2
    Any idea, how to fix this ??? Thanks a lot....

  • Dynamic sql and ref cursors URGENT!!

    Hi,
    I'm using a long to build a dynamic sql statement. This is limited by about 32k. This is too short for my statement.
    The query results in a ref cursor.
    Does anyone have an idea to create larger statement or to couple ref cursors, so I can execute the statement a couple of times and as an result I still have one ref cursor.
    Example:
    /* Determine if project is main project, then select all subprojects */
    for i in isMainProject loop
    if i.belongstoprojectno is null then
    for i in ProjectSubNumbers loop
    if ProjectSubNumbers%rowcount=1 then
    SqlStatement := InitialStatement || i.projectno;
    else
    SqlStatement := SqlStatement || PartialStatement || i.projectno;
    end if;
    end loop;
    else
    for i in ProjectNumber loop
    if ProjectNumber%rowcount=1 then
    SqlStatement := InitialStatement || i.projectno;
    else
    SqlStatement := SqlStatement || PartialStatement || i.projectno;
    end if;
    end loop;
    end if;
    end loop;
    /* Open ref cursor */
    open sql_output for SqlStatement;
    Thanks in advance,
    Jeroen Muis
    KCI Datasystems BV
    mailto:[email protected]

    Example for 'dynamic' ref cursor - dynamic WHERE
    (note that Reports need 'static' ref cursor type
    for building Report Layout):
    1. Stored package
    CREATE OR REPLACE PACKAGE report_dynamic IS
    TYPE type_ref_cur_sta IS REF CURSOR RETURN dept%ROWTYPE; -- for Report Layout only
    TYPE type_ref_cur_dyn IS REF CURSOR;
    FUNCTION func_dyn (p_where VARCHAR2) RETURN type_ref_cur_dyn;
    END;
    CREATE OR REPLACE PACKAGE BODY report_dynamic IS
    FUNCTION func_dyn (p_where VARCHAR2) RETURN type_ref_cur_dyn IS
    ref_cur_dyn type_ref_cur_dyn;
    BEGIN
    OPEN ref_cur_dyn FOR
    'SELECT * FROM dept WHERE ' | | NVL (p_where, '1 = 1');
    RETURN ref_cur_dyn;
    END;
    END;
    2. Query PL/SQL in Reports
    function QR_1RefCurQuery return report_dynamic.type_ref_cur_sta is
    begin
    return report_dynamic.func_dyn (:p_where);
    end;
    Regards
    Zlatko Sirotic
    null

  • Dynamic sql and block based on a stored procedure

    Hi!
    I'm triying to generate a block based on a stored procedure. I want the stored procedure to execute a dynamic sql, but I'm having getting the error "PLS-00455 cursor 'AULOCASLATE' cannot be used in dynamic SQL OPEN statement".
    I have the following code:
    CREATE OR REPLACE package pkg_f0015 is
    type rClieInstSlate is record
    (clie_id CMS_CLIENTS.ID%type
    ,client_nm varchar2(1000)
    ,cs_no CMS_CLIENTS.CS_NO%type
    ,dob CMS_CLIENT_NAMES.BIRTH_DT%type);
    type tClieInstSlate is table of rClieInstSlate;
    type uClieInstSlate is ref cursor return rClieInstSlate;
    procedure prLocationSlateQry(
    auLocaSlate in out uClieInstSlate,                anCsNo in CMS_CLIENTS.CS_NO%type,
    avClieNm in varchar2,
    avSearchType in varchar2,
    avLotyCd in CMS_LOCATION_TYPES.CD%type);
    end pkg_f0015;
    CREATE OR REPLACE PACKAGE BODY pkg_cms_f0015 is
    procedure PRLocationSlateQry( auLocaSlate in out uClieInstSlate,
    anCsNo in CMS_CLIENTS.CS_NO%type,
    avClieNm in varchar2,
    avSearchType in varchar2,
    avLotyCd in CMS_LOCATION_TYPES.CD%type) IS
    vSelect varchar2(5000);
    vAddCond varchar2(1000);
    vSupLevel varchar2(50);
    begin
    vSelect := 'select clie.ID,'||
    ' CLIENT_NAME,'||
    ' clie.CS_NO,'||
    ' clna.BIRTH_DT dob'
    ' from CMS_CLIENT_NAMES clna,'||
    'CMS_CLIENTS clie'||
    ' where clna.CLIE_ID = clie.ID';
    if avSearchType= 'C' then
    vAddCond := ' and clie.CS_NO = nvl('||anCsNo||',clie.CS_NO)';
    vSelect := vSelect || vAddCond;
    open auLocaSlate for vSelect;
    end if;
    end PRLocationSlateQry;
    end;
    I wonder if what I want is possible

    OK,
    Now it works. Previously we had the parameter p_guid declared as RAW, which obviously is not any good. :)
    Radovan
    Edited by: biciste on Apr 28, 2009 4:57 PM

Maybe you are looking for

  • Error authenticating proxy while running agent job

    I am trying to schedule a SSIS2014 package via SQL Server Agent job. Both SSIS and SSMS are running on my local machine in the same domain. I am running SSMS with the same user Domain\Admin which is the creator of the SSIS package. SSMS 32-Bit and SS

  • What happened to Camera Raw in Bridge CS6

    What is going on with Adobe? What happened to the Camera Raw features in Bridge CS6? It was working perfectly fine in previous versions. Working on a MAC, first sign, when I go in the AdobeBridge CS 6 drop down menu, select Camera Raw Preferences...

  • Why does my mac dont recognize the external hard drive

    i log the external HD, the lights on the Hd are going on (means electricity goes) but i cant see the thing inside the HD thank you som much for the help

  • Error when trying to sync - 'Unknown error (-48)' - HELP!

    Hi everyone Been having some iPod trouble this week - and now the next issue!! When I connect my iPod to my Mac, iTunes opens as it should, but then the following error pops up: The iPod cannot be synced. An unknown error occurred (-48). I haven't go

  • Controlling level of JPEG compression when exporting from iPhoto 6?

    Hi all, I'm wondering whether one can adjust the level of JPEG compression when exporting images? I'm still on iPhoto 4 that unfortunately doesn't offer this option and by default produces fairly large images that aren't well suited for web presentat