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

Similar Messages

  • Dynamic sql is throwing dump after upgrade to EHP 7.0

    Hi All,
    My customer recently upgraded to EHP 7.0.
    I have one query like below :
    select * from (ls_table_list-tabname) into
                             table <table>
                             where (condition).
    where ls_table-tabname is the table name, <table> is with the structure of same table and condition is very simple where condition. (id = 'XXXXX').
    We are getting dump with "CX_SY_DYNAMIC_OSQL_SYNTAX" and the dump message is "
    When parsing a dynamic statement, an error occurred.
    Before upgrade same statements were working fine.
    Please send us the response asap. Its urgent.
    Thanks in advance,
    Sreedhar

    Hi Divyanshu,
    Following is the text of Short dump :
    Category ABAP Programming Error
    Runtime error SAPSQL_PARSE_ERROR
    Exception CX_SY_DYNAMIC_OSQL_SYNTAX
    ABAP program / GETPF / SAPLTABLE_CONTENT_CHECK
    Application component not assigned
    Date and Time 07.02.2014 14:57:48
    Short text
    When parsing a dynamic statement, an error occurred.
    What happened?
    Error in ABAP application program.
    The current ABAP program "/ GETPF / SAPLTABLE_CONTENT_CHECK" had to be canceled
    be as it appears on
    an instruction is encountered, which unfortunately can not be executed.
    Error Analysis
    There is an exception has occurred, which is discussed further below.
    The exception, which is assigned to the class 'CX_SY_DYNAMIC_OSQL_SYNTAX'
    was in the procedure "/ GETPF / TABLE_CONTENT_CHECK" "(FUNCTION)" neither
    intercepted,
    still propagated by a RAISING clause.
    Since the caller of the procedure is not with the occurrence of the exception
    could be expected, the running program was terminated.
    Error was at below statement :
          SELECT * FROM (ls_table_list-tabname) INTO
    TABLE <table>
    WHERE (condition).

  • Creating Region & Items Dynamically based on SQL Result

    Hi,
    I need to create regions dynamically during runtime based on SQL.
    So the number of regions and title will depends on the SQL result.
    I came accross the PLSQL Dynamic Content region type. I searched in the internet, I could not find a matching example.
    I looked at the APEX book, it mentions about 'Creating a Matrix of Fields Programmatically' but It's not very descriptive and it's using www_flow_api which i couldn't find documentation about it.
    So I am turning into this forum for help.
    Can you guys guide me to dynamically create region in a page?
    for e.g
    If my sql returns 5 records, I need to create 5 regions. Each region will contain a dynamically created tabular form as well depending on another SQL (from table function).
    Please let me know if I am not being clear about my question.
    Thanks a lot in advance.

    hello,
    I have the following SQL statement in my region.
    SELECT APEX_ITEM.DISPLAY_AND_SAVE(1,rectype) rectype,
           APEX_ITEM.DISPLAY_AND_SAVE(2,class_id) class_id,
           APEX_ITEM.DISPLAY_AND_SAVE(3,attribute_id) attribute_id,
           decode(rectype,1,'<p style="font-size:17px;color:white;background-color:#383838">'||title||'</p>',
                          2,'<p><b><i><big>'||title||'</b></i></big></p>',
                          3,replace(title,chr(13)||chr(10),'</br>'),
                          apex_item.textarea(4,title,5,200)) title,
           decode(rectype,1,'<p style="font-size:17px;color:white;background-color:#383838">'||review1st||'</p>',
                          2,apex_item.text(5,review1st,3,3),
                          3,APEX_ITEM.SELECT_LIST_FROM_LOV(5,review1st,'ARTIST_RANK',null,'NO'),
                          apex_item.hidden(5,review1st)) review1st,
           decode(rectype,1,'<p style="font-size:17px;color:white;background-color:#383838">'||review2nd||'</p>',
                          2,apex_item.text(6,review2nd,3,3),
                          3,APEX_ITEM.SELECT_LIST_FROM_LOV(6,review2nd,'ARTIST_RANK',null,'NO'),
                          apex_item.hidden(6,review2nd)) review2nd
      FROM TABLE (pkg_artist_review.f_artist_review (:P21_ARTIST_SEQ, :P21_ARTIST_DISCIPLINE,:P21_REVIEW_YEAR))as you can see I use DECODE because I need to do HTML formatting on the value and create ITEM according to the value of 'rectype'
    decode(rectype,1,'<p style="font-size:17px;color:white;background-color:#383838">'||title||'</p>',
                          2,'<p><b><i><big>'||title||'</b></i></big></p>',
                          3,replace(title,chr(13)||chr(10),'</br>'),
                          apex_item.textarea(4,title,5,200)) title, so the report result would look like
    rectype                  title
    [display f01]          title
    [display f01]          title
    [display f01]          title
    [display f01]          [text area f04]My question is :
    I would think my array list f01 and f04 will have different number of values inside.
    f01 will have 4 value, whereas f04 will only have 1.
    I tried to use
    decode(rectype,1,APEX_ITEM.DISPLAY_AND_SAVE(4,'<p style="font-size:17px;color:white;background-color:#383838">'||title||'</p>'),
                          2,APEX_ITEM.DISPLAY_AND_SAVE(4,'<p><b><i><big>'||title||'</b></i></big></p>'),
                          3,APEX_ITEM.DISPLAY_AND_SAVE(4,replace(title,chr(13)||chr(10),'</br>')),
                          apex_item.textarea(4,title,5,200)) title, I only ended up having the HTML code written to the report.
    How can I handle such situation?
    I need my array list to have the same number of records thus i could just use one index to iterate through the value.
    Thanks in advance.
    Edited by: joel2 on Mar 18, 2009 3:40 PM

  • 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

  • BCP and dynamic SQL

    Hello All,
    Been looking into this for a couple of days, and I keep hitting brick walls, so I'm hoping someone can offer me a bit of inspiration. What I'm trying to do is write a stored procedure that lets the user specify a list of tables, and an output directory, and the SP creates a series of BCP statements that export these tables to comma delimited files.
    This wouldn't be too hard, but I need to output the field headings in the first row of the table (and use quotes as text qualifiers). I'm doing this by looping round sys.columns, pulling out all the fieldnames, creating two select statements, and UNION ALL-ing them together. e.g.......
    select 'FIELD1','FIELD2','FIELD3','FIELD4'
    union all
    select field1,field2,field3,field4 from tablename
    It all works fine until you try it on a table with a lot of columns. Although you can build a big SQL statement in an NVARCHAR(MAX), BCP only appears to read the first 4000 characters of it, so it fails.
    To get round this, I've moved all of the code that builds the big SQL statement to its own stored procedure (i.e. you pass the tablename, and it returns the table with the field names in the first row). Then, I can just call this new SP in my BCP statement, with a couple of parameters. 
    The problem I'm getting is BCP is complaining saying '[Microsoft][SQL Native Client]BCP host-files must contain at least one column'.  I'm setting no count off, and there are no print statements, so I'm assuming this is because the data is getting returned via an exec sp_executesq (although this is a guess). I can't think of a way round this though, as the SQL need to be dynamic.
    alter PROCEDURE [dbo].[sp_QBMultiFileExportGetData]
    @tablename varchar(100),
    @dbname varchar(100)
    AS
    BEGIN
    declare @Execstring as nvarchar(MAX)
    declare @currentfieldname as varchar(100)
    declare @selectlist as varchar(8000)
    declare @fieldnamelist as varchar(8000)
    declare @colnames table
    columnname varchar(100)
    begin
    set nocount on
    set @execstring='select COLUMN_NAME '+
    'from ' + @dbname + '.INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = ''' + @tablename + ''''
    insert into @colnames(columnname)
    exec sp_executesql @execstring
    set @selectlist=''
    set @fieldnamelist=''
    --Loop through fieldnames, and build two strings
    --One for outputting fieldnames and one for selecting the actual data
    while exists(select * from @colnames)
    begin
    select top 1 @currentfieldname=columnname from @colnames
    set @selectlist=@selectlist + 'quotename(['+ @currentfieldname + '],char(34)),'
    set @fieldnamelist=@fieldnamelist + '''' + @currentfieldname + ''' [' +@currentfieldname + '],'
    delete from @colnames where columnname=@currentfieldname
    end
    --remove last quote
    set @selectlist=substring(@selectlist,1,len(@selectlist)-1)
    set @fieldnamelist=substring(@fieldnamelist,1,len(@fieldnamelist)-1)
    --Built string to execute, with fieldnames, and select fields
    set @execstring='select ' + @fieldnamelist  + ' union all select ' + @selectlist + ' from ' + @dbname + '..'  + @tablename
    return exec sp_executesql @execstring
    end
    END
    this returns exactly what I want, but when I try to use it in a BCP statement, I get the error....
    i.e.
    EXEC master..xp_cmdshell 'bcp "exec QCDev.dbo.sp_QBMultiFileExportGetData ''tablename'',''dbname''" queryout C:\\outputfile.txt -T -t","'
    Error = [Microsoft][SQL Native Client]BCP host-files must contain at least one column
    Anyone ever tried this before?

    Hi Guys,
    Thanks for the suggestions. I had been trying to avoid temp tables (don't really like them), but I think eventually, they were the only way to go. Unfortunately, this opened a whole can of scoping worms, and after a couple of hours, its all given me a right headache. However, the good news is I've finally got it working as I wanted.
    I was finding I was having issues using temp tables, as the tables being used were dynamic, so I would have to create them in a dynamic SQL string, and they weren't propagating upwards from child to parent. I seemed to be getting the same problem using global temporary tables too, although I'm not sure why, as they should have worked They seemed to be out of scope by the time the SP that was calling my sp_QBMultiFileExportGetData tried to output the data. This might possibly have been because BCP wasn't seeing the same scope, but I've not tested it fully (and its very possible I was making a mistake).
    The solution was to abandon sp_QBMultiFileExportGetData, and merge the code back into the calling script. However, rather than trying to pass an enormous SQL string to bcp, running it separately with sp_executesql, and dumping the results in a global temp table. Then let bcp just call a 'select * from temptable', to avoid the select statement getting too long. Its not the most elegant solution, but it seems to work fine.
    ALTER PROCEDURE [dbo].[sp_QBMultiFileExport]
    -- Add the parameters for the stored procedure here
    @tablenames varchar(1000), --list of tables to be exported
    @outputpath varchar(1000), --output path ***AS SEEN BY THE SERVER, NOT THE CLIENT***
    @servername varchar(100), --Server where data resides
    @dbname varchar(100), --database name
    @delimiter varchar(1) --output delimiter
    AS
    BEGIN
    declare @Execstring as nvarchar(max)
    declare @currenttable as varchar(100)
    declare @colnames table
    columnname varchar(100)
    declare @currentfieldname as varchar(100)
    declare @selectlist as varchar(max)
    declare @fieldnamelist as varchar(max)
    --Get rid of CRLFs in the tablenames parameter
    set @tablenames=replace(@tablenames,char(10),'')
    set @tablenames=replace(@tablenames,char(13),'')
    --add extra comma to the end of the list (needed later for consistency)
    set @tablenames=@tablenames+','
    --Get first table in the list
    set @currenttable=substring(@tablenames,1,charindex(',',@tablenames)-1)
    while @tablenames<>''
    begin
    --Get a list of fieldnames from syscols
    insert into @colnames(columnname)
    select COLUMN_NAME
    from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @currenttable
    set @selectlist=''
    set @fieldnamelist=''
    while exists(select * from @colnames)
    begin
    --get first column name
    select top 1 @currentfieldname=columnname from @colnames
    --add to select statement lists
    set @selectlist=@selectlist + 'quotename(['+ @currentfieldname + '],char(34)),'
    set @fieldnamelist=@fieldnamelist + '''' + @currentfieldname + ''' [' +@currentfieldname + '],'
    --remove column from temptable
    delete from @colnames where columnname=@currentfieldname
    end
    --remove last quote from field lists
    set @selectlist=substring(@selectlist,1,len(@selectlist)-1)
    set @fieldnamelist=substring(@fieldnamelist,1,len(@fieldnamelist)-1)
    --check for temp table, and drop if necessary
    IF object_id('tempdb..##MultiFileExportTempTable') IS NOT NULL
    BEGIN
    DROP TABLE ##MultiFileExportTempTable
    END
    --Build list of fieldnames, and select list, unioned together
    --and put the results in temptable
    set @execstring='select ' + @fieldnamelist  + ' into ##MultiFileExportTempTable union all select ' + @selectlist + ' from ' + @dbname + '..'  + @currenttable
    exec sp_executesql @execstring
    --get BCP to pull data back from ##temptable, and dump in file
    set @execstring='EXEC master..xp_cmdshell ''bcp "select * from ##MultiFileExportTempTable" queryout ' + @outputpath + '\' + @currenttable + '.txt' + ' -c -T -t"' + @delimiter + '"'''
    exec sp_executesql @execstring
    --drop tablename from list
    set @tablenames=replace(@tablenames,@currenttable + ',','')
    --if tablenames list is not empty, get the next one
    if @tablenames<>''
    set @currenttable=substring(@tablenames,1,charindex(',',@tablenames)-1)
    else
    set @currenttable=''
    end
    IF object_id('tempdb..##MultiFileExportTempTable') IS NOT NULL
    BEGIN
    DROP TABLE ##MultiFileExportTempTable
    END
    END
    So, you call this with...
    exec dbo.[sp_QBMultiFileExport] 'table1,table2,table3',filepath,servername,dbname,delimiter
    ...and it creates delimited files called table1.txt, table2.txt and table3.txt in the specified folder, with field headings and text qualifiers.
    Many thanks for all your suggestions

  • RFC WHICH CAN USE DYNAMIC SQL AS INPUT AND SHOW COMPLETE DATA FOR TABLE

    Hi Expert,
    I am trying to create a FM like RFC_READ_TABLE. In this table we put table name and the field name for which we write a query and option for query we get the out put only for that field in this case.
    My requirement is very similar to this. But here i want to enter any table name and in option i want to write dynamic sql query for any filed of table then i want data based on this so that it will display the entire table entries.
    Like TABNAMELIKE     EKKO
    OTHERCON     bukrs_k = 3000.
    Based on this selection it has to show the entire table fields.
    To make this easy to understand i made a custom FM which are getting data from table or view and i select any field and put query it will show the result.
    FUNCTION ZDYNSQL_EKKO_EKPO.
    ""Local Interface:
    *"  IMPORTING
    *"     VALUE(ERNAMLIKE) TYPE  CHAR15 OPTIONAL
    *"     VALUE(OTHERCON) TYPE  CHAR50 OPTIONAL
    *"  TABLES
    *"      VALUE STRUCTURE  V_EKKO_EKPO
    *TABLES : V_EKKO_EKPO, EKKO, EKPO.
    DATA: STR_WHERE TYPE TABLE OF EDPLINE.
    DATA: STR_LINE TYPE EDPLINE.
    *CONCATENATE 'EBELN LIKE''' EBELNLIKE '%''' INTO STR_LINE.
            CONCATENATE 'ERNAM LIKE ''' ERNAMLIKE '%''' INTO STR_LINE.
            IF OTHERCON <> '            '.
            CONCATENATE STR_LINE 'AND' OTHERCON '            ' INTO STR_LINE SEPARATED BY SPACE.
            ENDIF.
          APPEND STR_LINE TO STR_WHERE.
          SELECT * FROM  V_EKKO_EKPO INTO CORRESPONDING FIELDS OF TABLE VALUE WHERE (STR_WHERE).
    ENDFUNCTION.
    Now here is sample code of exact requirement.
    FUNCTION ZDYNSQL_TABLE_READ.
    ""Local Interface:
    *"  IMPORTING
    *"     VALUE(TABNAMELIKE) TYPE  DD02L-TABNAME
    *"     VALUE(OTHERCON) TYPE  CHAR80 OPTIONAL
    *"  TABLES
    *"      VALUE STRUCTURE  DD02L
    DATA: STR_WHERE TYPE TABLE OF EDPLINE.
    DATA: STR_LINE TYPE STRING.
            CONCATENATE 'TABNAME LIKE ''' TABNAMELIKE '%' 'DD02L' 'TABNAME' INTO STR_LINE.
            IF OTHERCON <> '            '.
            CONCATENATE STR_LINE 'AND' OTHERCON '            ' INTO STR_LINE SEPARATED BY SPACE.
            ENDIF.
          APPEND STR_LINE TO STR_WHERE.
          SELECT * FROM DD02L INTO CORRESPONDING FIELDS OF TABLE VALUE WHERE (STR_WHERE).
    ENDFUNCTION.
    In this i put table name as EKKO and put sql query as bukrs_k = 3000 it provide a short dump.
    How can i solve this problem. Please provide some input or modification
    Thanks And Regards
    Ranjeet Singh

    Hi Kris,
    I tried to make sample using that link you provide to me. How can i declare Global Interface in FM and in import parameter references like "REFERENCE(I_INTERFACE_CHECK) DEFAULT SPACE".
    Also it uses a function-pool.
    Let me tell you about my exact requirement about FM.
    I want in import parameter input as any SAP Table name like
    TABNAME TYPE EKKO
    OPTIONS TYPE CHAR80
    I want my output to be stored in TABLES attributes as per the table name entered in import parameter. In import parameter Table name can be any one of SAP tables and Option based on that particular table. Like if i go with table EKKO and put OPTIONS as
    ebelp = 4 then TABLES attributes Tab  contains all the relevant data for input.
    Is there any way with the help of that i can put my data into internal tables. I tried to put in TABLES as VALUE LIKE ANY but it shows that generic are not allowed. Can you provide some sample on this.
    I also getting exceptions like CX_SY_DYNAMIC_OSQL_SEMANTICS, SAPSQL_INVALID_FIELDNAME.
    Waiting for your valuable reply.
    Thanks And Regards
    Ranjeet Singh

  • 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 255 bytes per line limit

    I would like to create a Dynamic SQL statement that is longer than 255 bytes. What do I need to do to embed a carriage return or something so that the resultant string is broken up into multiple lines?

    Please ignore. This was a stupid question!

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

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

  • Performance between SQL Statement and Dynamic SQL

    Select emp_id
    into id_val
    from emp
    where emp_id = 100
    EXECUTE IMMEDIATE
    'Select '|| t_emp_id ||
    'from emp '
    'where emp_id = 100'
    into id_valWill there be more impact in performance while using Dynamic SQL?

    CP wrote:
    Will there be more impact in performance while using Dynamic SQL?All SQLs are parsed and executed as SQL cursors.
    The 2 SQLs (dynamic and static) results in the exact same SQL cursor. So both methods will use an identical cursor. There are therefore no performance differences ito of how fast that SQL cursor will be.
    If an identical SQL cursor is not found (a soft parse), the SQL engine needs to compile the SQL source code supplied, into a SQL cursor (a hard parse).
    Hard parsing burns a lot of CPU cycles. Soft parsing burns less CPU cycles and is therefore better. However, no parsing at all is the best.
    To explain: if the code creates a cursor (e.g. INSERT INTO tab VALUES( :1, :2, :3 ) for inserting data), it can do it as follows:
    while More Data Found loop
      parse INSERT cursor
      bind variables to INSERT cursor
      execute INSERT cursor
      close INSERT cursor
    end loopIf that INSERT cursor does not yet exists, it will be hard parsed and a cursor created. Each subsequent loop iteration will result in a soft parse.
    However, the code will be far more optimal as follows:
    parse INSERT cursor
    while More Data Found loop
      bind variables to INSERT cursor
      execute INSERT cursor
    end loop
    close INSERT cursorWith this approach the cursor is parsed (hard or soft), once only. The cursor handle is then used again and again. And when the application is done inserting data, the cursor handle is released.
    With dynamic SQL in PL/SQL, you cannot really follow the optimal approach - unless you use DBMS_SQL (a complex cursor interface). With static SQL, the PL/SQL's optimiser can kick in and it can optimise its access to the cursors your code create and minimise parsing all together.
    This is however not the only consideration when using dynamic SQL. Dynamic SQL makes coding a lot more complex. The SQL code can now only be checked at execution time and not at development time. There is the issue of creating shareable SQL cursors using bind variables. There is the risk of SQL injection. Etc.
    So dynamic SQL is seldom a good idea. And IMO, the vast majority of people that post problems here relating to dynamic SQL, are using dynamic SQL unnecessary. For no justified and logical reasons. Creating unstable code, insecure code and non-performing code.

  • DBMS_SQL.TO_REFCURSOR and dynamic sql

    Hello,
    We've stored procedures that execute dynamic sql statements, an example template given below:
    create procedure sp_procedure1 (
    P_pselect_txt IN NVARCHAR2 DEFAULT NULL
    P_CV1 IN OUT PK_COM_DEFS.CV_TYP ) -- cv_typ is a loosely typed ref cursor.
    As
    begin
    open p_cv1 for p_select_txt;
    end;
    Now the issue is, open cursor do not support NVARCHAR2 data type. So, trying to use a new feature in 11g, DBMS_SQL.TO_REFCURSOR.
    Changed the above procedure as below:
    create procedure sp_procedure1 (
    P_pselect_txt IN NVARCHAR2 DEFAULT NULL
    P_CV1 IN OUT PK_COM_DEFS.CV_TYP ) -- cv_typ is a loosely typed ref cursor.
    As
    begin
    c number;
    r number;
    c:= dbms_sql.open_cursor;
    dbms_sql.parse (c, P_pselect_txt, dbms_sql.native);
    r := dbms_sql.execute(c);
    p_cv1 := dbms_sql.to_refcursor(c);
    dbms_sql.close_cursor (c);
    end;
    but getting "statement handle not executed" & access denied on sql.dbms_sql error messages.
    Could someone suggest how to change the above procedure to use dbms_sql.to_refcursor?
    thanks
    K.

    SQL> CREATE TABLE ntest (
      2  mycol NVARCHAR2(30));
    Table created.
    SQL> DECLARE
      2    rec_array SYS_REFCURSOR;
      3  BEGIN
      4    OPEN rec_array FOR
      5    'SELECT mycol FROM ntest';
      6  END;
      7  /
    PL/SQL procedure successfully completed.If you can not do this in your version then please post the results of this query:
    SELECT * FROM v$version;

  • Perfomance review Cursor and dynamic SQL

    Hi every one ,
    I searcher over internet and oracle forums for what is the best for my case.
    I tried to rebuild indexes . I had two methods , Both working fine but I am looking for what is better from performance point of view
    1- using Cursor like in the below link .
    http://www.think-forward.com/sql/rebuildunusable.htm
    2- Using Dynamic SQL , which generated script file then run it.
    spool rebuildall.sql
    select ' alter index '|| owner||'.'||index_name ||' rebuild online; '
    from dba_indexes where status='UNUSABLE';
    spool off;
    @rebuildall.sql
    Thanks in advance . Your help is appreciated.

    Hi ,
    Thanks for your input . We had some customer which they have a lot of row chaining and migration , I need to increase PCTFREE
    with move command . As result of this command indexes becomes unusable as you know . So there are monthly tables become chained with wrong definitions in PCTFREE and INTRSAN.
    I used the above script as help my time and solve problem faster ,It is only when I need it ,So it is not scheduled or something like that .
    I'm looking for anything will help and simplify the work .

  • Stored Procedures and Dynamic SQL

    In order to return query results from a PL/SQL procedure, I currently use an IN OUT parameter to return a cursor to JDBC.
    (Q: Is there any other way ???)
    But if I want to use dynamic SQL (DBMS_SQL) within the procedure, I don't know how to return the results. How do I get a handle on the DBMS_SQL underlying cursor, rather than just its cursor-ID?
    Can anyone help ?
    Thanks,
    Rob
    ([email protected])

    Very happy customer here!

Maybe you are looking for

  • IMac G5 came with 10.4, but restore CD has 10.3.7

    My iMac G5 1.8 Ghz came with 10.4.x preinstalled on it. I backed-up up to an external drive (with Backup 3) and reformatted my hard drive. When I went to reinstall my system, I found the Restore CD had 10.3.7 on it... so now I can only run Backup 2,

  • Output to textfiles in a jar file.

    To get what was in the text file i set it up liek this. BufferedReader d = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("Settings.txt"))); then String str= d.readLine(); and so on. How would i output to that file in my jar?

  • Problem of "assembly" HRESULT

    I can not download iTunes as it should he warned me of a problem of "assembly" HRESULT

  • Tabs and leader

    Couple of questions for all of the ID experts out there. Thank you Peter for responding to my last post...this project is still very much a work in progress. Unfortunately it has fallen on my lap as a last minute project and has given me little time

  • ITunes Equalizer will not open

    I just upgraded to the latest version of ITunes and the equalizer does not open. A window opens but there's nothing there??? Running win xp pro. Everything else is fine. Anybody got any ideas? Thanks Think Pad T60   Windows XP Pro