Check Results of Dynamic SQL- Oracle

Hi,
Can anyone help me to know if I can use a check to verify if a Dynamic SQL query returns NO ROWS.
Suppose:
LC_SQL := 'select * from tableA'
EXECUTE IMMEDIATE LC_SQL;
I now need to check if on execution LC_SQL fetches 0 rows.

Few modifications required.
declare
v_count number;
lc_sql varchar2(200);
begin
LC_SQL := 'select count(*) from tableA';
EXECUTE IMMEDIATE LC_SQL into V_COUNT;
IF V_COUNT = 0
     then
          dbms_output.put_line('NO ROWS RETURNED');
    else
        dbms_output.put_line('Data Exists');
end if;
end;
BTW, if the requirement is to check if data is there in the table or not, there is no need of using Dynamic SQL. If you are checking the data for multiple tables and table names are dynamic, then you need to go with Dynamic SQL.
Ishan

Similar Messages

  • Put results of dynamic sql into pl/sql table

    Hi.
    I tried to "google up" solution to my problem but in vain, so if possible could you give me a hint?
    The test code which I will paste here is somewhat akward, it is part of bigger code and I tried to simplify and adjust it.
    The problem is:
    I have sql statement which I construct on the run, and I want to put results of this statement into collection.
    With present code I get "ORA-00932: inconsistent datatypes".
    The collection must be global, since later on I need to do selects from this collection using:
    select col_1, col_2, col_3 from table(cast(v_pole_final as t_pole)))
    And I do not want put constructors into sql statements (which i believe would help).
    The select will always return columns types varchar, number, number.
    I.e. the same structure as in type "t_zaznam".
    I want to use "execute immediate", or "ref cursor - fetch bulk collect into collection".
    Thanks for help.
    Jan
    -------------- My code:
    create or replace type t_zaznam is object (col_1 varchar2(64), col_2 number, col_3 number);
    create or replace type t_pole is table of t_zaznam;
    create or replace function sulc_experim return number
    is
    s_sql_temp varchar2(6000):= 'select ''asdf asdf'', 7, 777 from dual '||
    ' union '||
    ' select ''yes boss'', 1, 111 from dual'||
    ' union '||
    ' select ''go home'', 9, 999 from dual';
    v_pole t_pole:= t_pole();
    v_pole_final t_pole:= t_pole();
    begin
    execute immediate s_sql_temp into v_pole;
    return 0;
    end sulc_experim;

    user5714007 wrote:
    Thank you.
    I think this is what I meant by "And I do not want put constructors into sql statements (which i believe would help)."
    It would be helpful to be able to select "on the fly" also multiple-columns and mainly multiple-rows results into collection.In case you didn't notice: The deciding difference that Karthik made was this line:
    execute immediate s_sql_temp bulk collect into v_pole;
    If that is not the trouble you have, then please explain you problem with a few samples. What works and what does not work.
    Also there is always dbms_sql where you can create the paramters/output types "on the fly".

  • SQL check result of the sql statement

    hello gurus, i have this sql statement:
    select MyTableColumn_PDF_File
    from Database.dbo.MyTableName
    where coalesce( MyTableColumn_PDF_File,' ') is null;
    so basically, it works fine on sql management studio.
    But what if I used this command on vb.net, how do I check whether the column is null or not?
    Any help is greatly appreciated.
    Thanks. :)
    Every second counts..make use of it. Disclaimer: This posting is provided AS IS with no warranties or guarantees and confers no rights.
    IT Stuff Quick Bytes

    Dim con As New SqlClient.SqlConnection("connectionstring")
    Dim DR As SqlClient.SqlDataReader = Nothing
    Try
    con.Open()
    Dim cmd As New SqlClient.SqlCommand("select COUNT(*) AS TotalNull " & _
    "from Database.dbo.MyTableName " & _
    "where MyTableColumn_PDF_File is null", mSQLConnection)
    DR = cmd.ExecuteReader()
    If DR.Read Then
    '' found rows
    If CInt(DR.Item("TotalNull")) <> 0 Then
    '' We have more than 1 row that is not null
    End If
    Else
    '' not found nows
    End If
    Catch ex As Exception
    ''' oops
    Finally
    If Not IsNothing(DR) Then
    If Not DR.IsClosed Then DR.Close()
    DR = Nothing
    End If
    If Not IsNothing(con) Then
    If con.State = ConnectionState.Open Then con.Close()
    con = Nothing
    End If
    End Try
    This is a more complete example

  • Can we use Dynamic SQL in Oracle Reports ?

    Hi ,
    Can we use Dynamic SQL in Oracle Reports ?
    If yes please give some examples .
    Thanx
    srini

    I believe the built-in package SRW.Do_Sql is what you are looking for
    Example from the document:
    /* Suppose you want to create a "table of contents" by getting the
    ** first character of a columns value, and page number on which its
    ** field fires to print. Assume that you want to put the "table of
    contents"
    ** into a table named SHIP. You could write the following construct:
    DECLARE
    PAGE_NO NUMBER;
    PAGE_FOR INDEX NUMBER;
    SORT_CHAR CHAR(1);
    CMD_LINE CHAR(200);
    BEGIN
    SORT_CHAR := :SORT_NAME ;
    IF :CALLED = Y THEN
         SRW.GET_PAGE_NUM(PAGE_FOR_INDEX);
         SRW.USER_EXIT(RWECOP PAGE_FOR_INDEX
         P_START_PAGENO);
         SRW.MESSAGE(2,TO_CHAR(:P_START_PAGENO));
    END IF;
    SRW.GET_PAGE_NUM(PAGE_NO);
    CMD_LINE := INSERT INTO SHIP VALUES
                          (||SORT_CHAR||,||TO_CHAR(PAGE_NO)||);
    SRW.MESSAGE(2,CMD_LINE);
    SRW.DO_SQL(CMD_LINE);
    COMMIT;
    EXCEPTION
      WHEN DUP_VAL_ON_INDEX THEN
            NULL;
      WHEN SRW.DO_SQL_FAILURE THEN
            SRW.MESSAGE(1,FAILED TO INSERT ROW INTO SHIP TABLE);
      WHEN OTHERS THEN
           COMMIT;
    END;

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

  • Whether timestamp types are supported in oracle dynamic sql?

    Oracle has two dynamic sql models. The old and the new ANSI model. I wish to know where and how the timestamp oracle data types are supported.
    I am having trouble setting the timestamp data through pro*c using old dynamic sql. I tried to set it to raw 11 bytes and use type 187 (timestamp) and it segfaults! I try now to set it to string type and oracle says invalid month! I tried even using nls_timestamp_format setting but no luck. Obviously some thing is amiss.
    Can some body help me?
    I need this info rather urgently.
    Thanks.

    Yes it is possible
    TO_DATE(:variable,'FORMAT') in dynamic SQL

  • Delcare Cursor using Dynamic SQL using PL/SQL in Oracle 7.3.4

    In Oracle 7.3.4, can I declare a cursor at run time using Dynamic SQL. From the sample code in this website, it seems that Oracle 8 support this function. Please help. Thanks a lot.
    If I can do this on Oracle 7.3.4, could you give me some sample codes? Thanks.
    Regards,
    Raymond

    Hi,
    Try using the the following code where you can dynamically build the Valid Select stmt. and call that where ever you want.
    declare
    Type Cur_ref Is Ref Cursor;
    C_ref Cur_ref;
    V_Str Varchar2(100);
    V_Name Varchar2(100);
    Begin
    V_Str := 'Select Ename from Scott.emp Where empno = 7369';
    Open C_Ref for V_Str;
    Fetch C_ref Into V_Name;
    close C_Ref;
    dbms_output.put_line(V_Name);
    End;
    regards
    gaurav
    null

  • Oracle to MS SQL porting - dynamic sql - cursors

    I have a stored procedure written for oracle which needs to be ported to MS SQL. Used SSMA to do that but the dynamic sql statements are not getting ported and are the same. Below is a dynamic sql from the SP after making changes with SSMA.
    SET @dsql_statement =
    'declare '
    +
    ' p table_name%rowtype;'
    +
    ' c table_name%rowtype;'
    +
    ' TYPE DAT IS REF CURSOR;'
    +
    ' type dtt is table of table_name1%rowtype index by binary_integer;'
    +
    ' d dtt;'
    +
    ' aRC DAT;'
    +
    ' sq varchar2(1000);'
    +
    ' i NUMBER:=0;'
    +
    ' attributeLabel nvarchar2(255);'
    +
    ' attributename nvarchar2(255);'
    +
    ' attributetype nvarchar2(255);'
    +
    ' fkvalue nvarchar2(255);'
    +
    ' defaultfield nvarchar2(80);'
    +
    ' tablename nvarchar2(80);'
    +
    ' primarykeyfield nvarchar2(80);'
    +
    ' begin '
    +
    ' sq:=''SELECT * FROM mdbadmin.table_name WHERE lower(COLUMN1) IN'
    +
    ' (''''update'''',''''insert'''') AND COLUMN2 >= '
    +
    ISNULL(CAST(@COLUMN2 AS nvarchar(max)), '')
    +
    +
    ' ORDER BY COLUMN3,COLUMN2 ASC'';'
    +
    ' open aRC for sq;'
    +
    ' fetch aRC into c;'
    +
    ' loop '
    +
    ' fetch aRC into p;'
    +
    ' exit when aRC%NOTFOUND;'

    Some thing like
    dsql_statement :=  'begin '
    || ' for I in (SELECT * FROM mdbadmin.table_name WHERE lower(COLUMN1) IN '
    || ' (''update'',''insert'') AND COLUMN2 >= '
    || 'NVL(to_char('||'@COLUMN2'||'), '''') '
    || ' ORDER BY COLUMN3,COLUMN2 ASC ) '
    || 'loop '
    || 'end loop; '
    || 'end; '
    you can use for loop instead

  • Avoid Hard Parsing for executing dynamic SQL using DUAL table Oracle

    I want to know if dynamic sql statements involving DUAL table can be modified to remove HARD PARSING.
    We have several SQL statements are stored in configuration table, here is sample example
    -- query 1 before replacing index values as stored in config table ---
    select count(*) from dual where  'REPLACE_VALUE_OF_INDEX_3' IN ('K')
    AND (('REPLACE_VALUE_OF_INDEX_13' IN ('1053','1095','1199') ) OR ('REPLACE_VALUE_OF_INDEX_13' IN ('1200') ))
    AND 'REPLACE_VALUE_OF_INDEX_2' IN ('6')
    AND 'REPLACE_VALUE_OF_INDEX_15' IN ('870001305')
    -- query 1 after replacing index values--
    select count(*) from dual where  'REPLACE_VALUE_OF_INDEX_10' IN ('K')
    AND (('1030' IN ('1053','1095','1199') ) OR ('1030' IN ('1200') ))
    AND '2' IN ('6')
    AND 'X' IN ('870001305')
    -- query 2 before replacing index values as stored in config table --
    select count(*) from dual where  'REPLACE_VALUE_OF_INDEX_5' IN ('361A','362A')
    AND 'REPLACE_VALUE_OF_INDEX_22' BETWEEN '200707' AND '200806'
    -- query 2 after replacing index values--
    select count(*) from dual where  '3MAA' IN ('361A','362A') AND '201304' BETWEEN '200707' AND '200806'

    If I got it right you have some (maybe lots of) conditions stored in a table (be patient - it's my interpretation)
    create table eb_conditions as
    select 1 rid,q'{:5 IN ('361A','362A') AND :3 BETWEEN '200707' AND '200806'}' cndtn from dual union all
    select 2,q'{:2 IN ('361A','362A') AND :3 BETWEEN '200707' AND '200806'}' from dual union all
    select 3,q'{:1 IN ('K') AND ((:2 IN ('1053','1095','1199') ) OR (:4 IN ('1200') )) AND :3 IN ('6') AND :5 IN ('870001305')}' from dual
    RID
    CNDTN
    1
    :5 IN ('361A','362A') AND :3 BETWEEN '200707' AND '200806'
    2
    :2 IN ('361A','362A') AND :3 BETWEEN '200707' AND '200806'
    3
    :1 IN ('K') AND ((:2 IN ('1053','1095','1199') ) OR (:4 IN ('1200') )) AND :3 IN ('6') AND :5 IN ('870001305')
    and you have to check the conditions using values stored in an array
    I used a table instead: the vl at rid = 1 representing the value of bind variable :1 in eb_conditions table and so on ...
    create table eb_array as
    select 1 rid,'K' vl from dual union all
    select 2,'1199' from dual union all
    select 3,'200803' from dual union all
    select 4,'1000' from dual union all
    select 5,'870001305' from dual
    RID
    VL
    1
    K
    2
    1199
    3
    200803
    4
    1000
    5
    870001305
    You want to check the conditions using select count(*) from dual where <condition with binds substituted fron the array>
    Judging from the title Hard Parsing represents the major problem and you cannot avoid it since every condition to be verified is different from every other condition.
    I think your best bet is not to evaluate conditions row by row - context shift cannot be avoided and there might be more than one for each iteration.
    So try to do it in a single step:
    declare
    w_cndtn varchar2(4000);
    w_clob  clob;
    w_cursor sys_refcursor;
    one number;
    two number;
    begin
      dbms_lob.createtemporary(w_clob,false);
      for rw in (select rid,
                        max(cndtn) cndtn,
                        listagg(val,',') within group (order by rn)||',' usng
                   from (select c.rid,c.cndtn,c.rn,c.bind,
                                replace(rtrim(c.bind),':'||to_char(v.rid),''''||v.vl||'''') val
                           from (select rid,
                                        cndtn,
                                        regexp_substr(cndtn,':\d+ ',1,level) bind,
                                        level rn
                                   from eb_conditions
                                 connect by level <= regexp_count(cndtn,':')
                                        and prior rid = rid
                                        and prior sys_guid() is not null
                                ) c,
                                eb_array v
                          where instr(c.bind,':'||v.rid||' ') > 0
                  group by rid
      loop
        w_cndtn := rw.cndtn;
        while instr(w_cndtn,':') > 0
        loop
          w_cndtn := replace(w_cndtn,trim(regexp_substr(w_cndtn,':\d+ ',1,1)),substr(rw.usng,1,instr(rw.usng,',') - 1));
          rw.usng := substr(rw.usng,instr(rw.usng,',') + 1);
        end loop;
        w_cndtn := 'select '||to_char(rw.rid)||' cndtn_id,count(*) from dual where '||w_cndtn||' union all ';
        w_clob := w_clob ||' '||w_cndtn;
      end loop;
      w_clob := substr(w_clob,1,instr(w_clob,'union all',-1,1) - 1);
      open w_cursor for w_clob;
      loop
        fetch w_cursor into one,two;
        exit when w_cursor%notfound;
        dbms_output.put_line(to_char(one)||':'||to_char(two));
      end loop;
      dbms_lob.freetemporary(w_clob);
    end;
    1:0
    2:0
    3:0
    Statement processed.
    Regards
    Etbin

  • Dynamic SQl results in DUMP

    Does someone see what is wrong in my dynamic SQL statement is reuslts in a dump!
    DUMP and CODE below!
    Runtime error          SAPSQL_WHERE_MISSING_VALUE                                                  
    Except.                CX_SY_DYNAMIC_OSQL_SYNTAX                                                   
    Datum en tijd          19.02.2009 13:30:13                                                                               
    Korte tekst                                                                               
    A comparison value is missing in a condition specified dynamically.                                                                               
    Wat is er gebeurd?                                                                               
    Error in the ABAP Application Program                                                                               
    The current ABAP program "!PR_RVVEEN_USED_FIELDS" had to be terminated because                
          it has                                                                               
    come across a statement that unfortunately cannot be executed.                                                                               
    Foutenanalyse                                                                               
    An exception occurred that is explained in detail below.                                      
         The exception, which is assigned to class 'CX_SY_DYNAMIC_OSQL_SYNTAX', was not                
          caught and                                                                               
    therefore caused a runtime error.                                                             
         The reason for the exception is:                                                              
         The current ABAP program has tried to execute an Open SQL statement                           
         in which a condition was (partially) specified dynamically. In the                            
         part specified at runtime, the program expects to find a literal as                           
         the comparison value.                                                                               
    ===============================================
    itable = 'pa0001'
      CALL FUNCTION 'DD_NAMETAB_TO_DDFIELDS'
        EXPORTING
          tabname  = iname
        TABLES
          ddfields = ddfields.
      LOOP AT ddfields.
    data: where_tab(30) occurs 1 with header line,
    where_clause(30) type c.
    concatenate ddfields-fieldname '<> " "' into where_clause SEPARATED BY space.
    append where_clause to where_tab.
    select pernr from (itable) into table lt_pernr where (where_tab).
      if sy-subrc = 0.
        write 'FIELD COTAINS A VALUE'.
      endif.
      ENDLOOP.

    I'm also missing a dot ('.') at the end of the line. Command should always end with a point.
    For numeric characters you can use '0000' (depending on number of characters).
    BTW. you are creating the dynamic where clause within the loop, without clearing (initializing ) anything. This will lead to the next problem.
    Edited by: Micky Oestreich on Feb 19, 2009 2:13 PM

  • Dynamic SQL in non oracle Data Template

    Hi All
    I am currently working on a project with BI Publisher and we are developing on an OBIEE data source using data templates.
    Does anyone know how to handle dynamic sql &Lexicals when your only data source is OBIEE.
    I have found some code in the help which doesn't seem to work.
    {$ if ${P_COUNTRY} = '*,*' $}
    WHERE "Customers"."Country" in (&P_COUNTRY)
    {$ elsif ${P_COUNTRY} = '*' $}
    WHERE "Customers"."Country" = :P_COUNTRY
    {$ else $}
    {$ endif $}
    Thanks
    Andy

    Hi Andy,
    If you are using Answers as data source, Dynamic query is not possible.

  • 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

  • Callprocedure which contain dynamic sql that retrieve multiple records from VB

    hi dear i have problem with using dynamic sql to retrieve multipule records
    and access them from visual basic
    first i use Oracle8 Enterprise Edition Release 8.0.4.0.0
    and odbc microsoft odbc for oracle version 2.573.4403.00
    these are the whole processes to do that
    please check the steps and if u find any error say to me....
    1-table description
    Name Null? Type
    PORT_KEY NOT NULL VARCHAR2(4)
    CITY_KEY NOT NULL VARCHAR2(4)
    and port_key is primary key
    2- package declaration
    create or replace package ww1
    as
    procedure bound_type
    (v_origin in varchar2,v_flag in varchar2
    ,city_key out dbms_sql.varchar2_table
    end ;
    3- package body
    create or replace package body ww1
    as
    procedure bound_type
    (v_origin in varchar2,v_flag in varchar2
    ,city_key out dbms_sql.varchar2_table
    is
    str varchar2(1000);
    cur_hdl integer :=dbms_sql.open_cursor;
    rows_processed integer;
    indx integer :=1;
    begin
    str:='select ltrim(rtrim(city_key)) from special_airport ';
    if ltrim(rtrim(upper(v_flag))) = upper('c')
    then
    str:=str &#0124; &#0124; ' where city_key=ltrim(rtrim(upper('&#0124; &#0124;''''&#0124; &#0124;v_origin&#0124; &#0124;''''&#0124; &#0124;')))';
    elsif ltrim(rtrim(upper(v_flag))) = upper('a') then
    str:= str &#0124; &#0124;' where port_key=ltrim(rtrim(upper('&#0124; &#0124;''''&#0124; &#0124;v_origin&#0124; &#0124;''''&#0124; &#0124;')))';
    end if;
    dbms_sql.parse(cur_hdl,str, dbms_sql.native );
    dbms_sql.define_array(cur_hdl,1,city_key,10,indx);
    rows_processed:=dbms_sql.execute(cur_hdl);
    loop
    rows_processed:=dbms_sql.fetch_rows(cur_hdl);
    dbms_sql.column_value(cur_hdl,1,city_key);
    exit when rows_processed != 10;
    end loop;
    dbms_sql.close_cursor(cur_hdl);
    end bound_type;
    end ww1;
    4- code for calling stored procedure from visual basic
    dim c As New ADODB.Connection
    Dim cmd As New ADODB.Command
    Dim rs As New ADODB.Recordset
    c.Open "dsn=dsnName;uid=uidValue;pwd=pwdValue"
    With cmd
    Set .ActiveConnection = c
    .CommandType = adCmdText
    '---------(call bound_type stored procedure)--------------
    .Parameters.Append .CreateParameter(, adBSTR, adParamInput, , "bwi")
    .Parameters.Append .CreateParameter(, adBSTR, adParamInput, , "a")
    .CommandText = "{call fares_procedures.bound_type (?,?,{resultset 10, city_key }) }"
    End With
    Set rs.Source = cmd
    rs.Open
    While Not rs.EOF
    z = rs.Fields("city_key")
    rs.MoveNext
    Wend
    Set cmd = Nothing
    rs.Close
    Set rs = Nothing
    c.Close
    Set c = Nothing
    ***********result get error*************
    please check the code and steps and if u find any error contact me
    thanks any way
    null

    hi every one i got a simple solusion and its faster than dbms_sql package by 1.5 to 3 times...but it works only for oracle 8i or higher......
    after concatenat the string of dynamic sql
    but it in a ref cursor and loop on it
    TYPE VAR_TABLE IS TABLE OF VARCHAR2(40)
    INDEX BY BINARY_INTEGER;
    procedure bound_type
    (v_origin in varchar2,v_flag in varchar2
    ,city_key out var_table )
    is
    str varchar2(1000);
    type curtype is ref cursor;
    sa_cur curtype;
    i integer default 1;
    begin
    str:='select ltrim(rtrim(city_key)) from special_airport ';
    if ltrim(rtrim(upper(v_flag))) = upper('c')
    then
    str:=str &#0124; &#0124; ' where city_key=ltrim(rtrim(upper('&#0124; &#0124;''''&#0124; &#0124;v_origin&#0124; &#0124;''''&#0124; &#0124;')))';
    elsif ltrim(rtrim(upper(v_flag))) = upper('a') then
    str:= str &#0124; &#0124;' where port_key=ltrim(rtrim(upper('&#0124; &#0124;''''&#0124; &#0124;v_origin&#0124; &#0124;''''&#0124; &#0124;')))';
    end if;
    open sa_cur for str;
    loop
    fetch sa_cur into city_key(i);
    exit when sa_cur%notfound;
    i:=i+1;
    end loop;
    close sa_cur;
    end bound_type;
    null

  • Unique id in dynamic sql

    hi all,
    I am using oracle 10g version.
    I have one table but i do not have any unique id to identify the row.
    I want to have a unique id temporarily in my select statement (dynamic sql) in a stored procedure while fetching the results, so that i can return my results along with the unique id through the cursor.
    Please help me...
    Thanks in advance to all...

    it depends if you have a more than one column that you can uniquely identify and put them together by concatenating you can have a unique id. or a rowid might help you to temporarily identify a row.
    SQL> select e.* from employee e;
    FNAME           MINIT LNAME           SSN       BDATE       ADDRESS                        SEX       SALARY SUPERSSN         DNO
    John            B     Smith           123456789 09-Jan-1965 731 fONDREN, hOUSTON, TX       M       30000.00 333445555          5
    Frankin         T     Wong            333445555 08-Dec-1955 683 Voss, Houston,Tx           M       40000.00 888665555          5
    Alicia          J     Zelaya          999887777 19-Jul-1968 3321Castle, Spring, TX         F       25000.00 987654321          4
    Jennifer        S     Wallace         987654321 20-Jun-2041 291 Berry, Bellaire, TX        F       43000.00 888665555          4
    Ramesh          K     Narayan         666884444 15-Sep-1962 975 Fire Oak, Humble, TX       F       38000.00 333445555          5
    Joyce           A     English         453453453 31-Jul-1972 5631 Rice,Houston,TX           F       25000.00 333445555          5
    Ahmad           V     Jabbar          987987987 29-Mar-1969 980 Dallas,Houston, TX         M       25000.00 987654321          4
    James           E     Borg            888665555 10-Nov-2037 450 Stone, Houston, TX         M       55000.00                    1
    8 rows selected
    SQL> select rowid, e.* from employee e;
    ROWID              FNAME           MINIT LNAME           SSN       BDATE       ADDRESS                        SEX       SALARY SUPERSSN         DNO
    AAD8pbAAJAAAJ4fAAA John            B     Smith           123456789 09-Jan-1965 731 fONDREN, hOUSTON, TX       M       30000.00 333445555          5
    AAD8pbAAJAAAJ4fAAB Frankin         T     Wong            333445555 08-Dec-1955 683 Voss, Houston,Tx           M       40000.00 888665555          5
    AAD8pbAAJAAAJ4fAAC Alicia          J     Zelaya          999887777 19-Jul-1968 3321Castle, Spring, TX         F       25000.00 987654321          4
    AAD8pbAAJAAAJ4fAAD Jennifer        S     Wallace         987654321 20-Jun-2041 291 Berry, Bellaire, TX        F       43000.00 888665555          4
    AAD8pbAAJAAAJ4fAAE Ramesh          K     Narayan         666884444 15-Sep-1962 975 Fire Oak, Humble, TX       F       38000.00 333445555          5
    AAD8pbAAJAAAJ4fAAF Joyce           A     English         453453453 31-Jul-1972 5631 Rice,Houston,TX           F       25000.00 333445555          5
    AAD8pbAAJAAAJ4fAAG Ahmad           V     Jabbar          987987987 29-Mar-1969 980 Dallas,Houston, TX         M       25000.00 987654321          4
    AAD8pbAAJAAAJ4fAAH James           E     Borg            888665555 10-Nov-2037 450 Stone, Houston, TX         M       55000.00                    1
    8 rows selected
    SQL>

  • 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

Maybe you are looking for