Dynamic sql execution with quotes

I have an application that allows users to submit an sql statement arbitrary (like DELETE and INSERT keywords are not allowed, in case you're wondering). I send the string to theSQL Server stored procedure below. The problem is that I get an error when the sql statement contains quotes like this:

Select companyName top 10
customers
where country = "USA".

All solutions? Thank you.

Pete

By default, the CF escapes apostrophes found in the string in a variable
passed to a tag. This should allow this use case for
work correctly.


INSERT INTO Àtable (far)
(#aVar #)

ColdFusion will escape the single quotes in the string by doubling the
to make this work correctly. In your case, you do not want eluded them,.
and preserveSingleQuotes() function to tell CF to not do it.

>
> #preserveSingleQuotes (form.queryString) #.
>

Tags: ColdFusion

Similar Questions

  • Char invalid when you use dynamic sql statements with cursor

    Hello guys,.
    I'm opening a following cursor with dynamic sql
     v_sql := 'SELECT OS.table_name FROM OBJECT_STATS_CONTROL OS, ALL_TABLES AT
                    WHERE OS.analyze_flag <> ''N''
                    AND OS.last_analyze < sysdate -1 AND AT.last_analyzed < sysdate - 1 '||v_1||';'; 
    my cursor statement is
    BEGIN
           OPEN v_cur FOR v_sql; 
           LOOP
           FETCH v_cur INTO v_tabname;
    ......
    I get an error message
    0911 invalid char
    can any body suggest me where I'm wrong

    Thank you

    Remove the semicolon at the end:

    ||';'  -- remove this.
    
  • The USE of dynamic SQL clause

    Hi all
    I'm moving a table as a variable in dynamic SQl but with no result. Suppose that I it running on HR diagram example:
    declare
    sql_state varchar(100);
    hire_date date;
    temp_table varchar(9):='employees';
    
    begin
    sql_state:= 'select hire_date from :1 where employee_id=206';
    
    execute immediate sql_state into hire_date using temp_table;
    dbms_output.put_line('hire_date is '||hire_date);
    end; 
    
    declare
    *
    ERROR at line 1:
    ORA-00903: invalid table name
    ORA-06512: at line 9
    I get this error of invalid table name without knowing what was read for the variable. Any advice?

    Best regards
    Val

    Hi Valerie,

    To add to what Peter, said

    "Binding" values in a query is done for a specific purpose, and this purpose is so that the optimizer can use the same query as the previous execution plan runs the query, which prevent it from having to analyze the hard the query each time. A query execution plan is based on the tables and columns are presented in the query, but with respect to the actual "values" of these columns, they are unlikely to change the execution plan. So, to keep the same execution plan, the query must seem identical (in terms of a query string) like the previous series, so if you want the same query, but just with different values, they can be replaced with bind variables (these things have a ': ' character) and then the values passed in the query, when it is run.

    Now, if Oracle were to allow you to link in the names of objects, such as tables, this means that it could not use the previous execution plans, because he doesn't know until run time what tables will be consulted. Therefore, it would be useless link in the values of the query and it would be just as quick to implement your query string by concatenating all the values inside rather than link them. Considering that a query is parsed first and then the values in it, then it cannot be analyzed if the tables are not known everything first. (Take a look at how queries are formed and variables when you use the DBMS_SQL package).

    So the key thing to remember is that, when it comes to bind variables, you can bind only the 'values', not 'objects '.

  • Quoted string inside dynamic SQL

    Hello
    My version of db: database Oracle 11 g Enterprise Edition Release 11.2.0.1.0 - 64 bit Production

    I run this code in a proc, and it goes to the exception block without running the code below:
    EXECUTE IMMEDIATE
        'SELECT LISTAGG (entitlement, '''','''') WITHIN GROUP (ORDER BY entitlement)
        FROM XMLTABLE (                                 
            ''''/ROWSET/ROW/ENTITLEMENTS/ENTITLEMENT''''      
            PASSING XMLPARSE (DOCUMENT p_xmldoc)        
            COLUMNS ENTITLEMENT VARCHAR2(30) PATH ''''.'''')'                                    
        INTO v_str;
    I made a mistake with quoted strings and I have tried different combinations, but anyway his does not work.
    THA real piece of code is below, whick I'm trying to run immediately in a string
    SELECT LISTAGG (entitlement, ',') WITHIN GROUP (ORDER BY entitlement)                              
                                            FROM XMLTABLE (                                 
                                                '/ROWSET/ROW/ENTITLEMENTS/ENTITLEMENT'      
                                                PASSING XMLPARSE (DOCUMENT p_xmldoc)        
                                                COLUMNS ENTITLEMENT VARCHAR2(30) PATH '.')
    p_xmldoc sample is less than
    '<?xml version="1.0"?>
    <ROWSET>
    <ROW>
    <ENTITLEMENTS>
      <ENTITLEMENT>AMEX</ENTITLEMENT>
      <ENTITLEMENT>JCB</ENTITLEMENT>
    </ENTITLEMENTS>
    </ROW>
    </ROWSET>'
    My goal is to get
    v_str = AMEX, JCB
    Please advice.

    Hello

    Use the notation by Q.
    Assuming that the dynamic control does not contain a right brace immediately before a single quote, you can say:

    
    sql_txt := Q'{SELECT LISTAGG (entitlement, ',') WITHIN GROUP (ORDER BY entitlement) ...}';
    dbms_output.put_line (sql_txt || ' = sql_txt');
    -- EXECUTE IMMEDIATE sql_txt;
    

    With Q-rating, you can't excape double, or otherwise single quotes.

    When you write code dynamic SQL, put the full command in a single VARCHAR2 variable (such as the sql_txt above). During the test, display it. If it looks right, then a comment the line where actually run you it.

  • Dynamic SQL with dynamic identifiers

    Oracle 10gXE

    I have a table that is used to track student attendance. If the student is present on a given day, a record is inserted with the student ID and the date they frequented.

    presence of DESC
    Name of Type Null
    --------------- -------- ------
    ID NOT NULL NUMBER
    NUMBER OF STUDENT_ID
    SITE_ID NUMBER
    DATE OF ATTENDANCE_DATE

    I want to view a report (in TOP) which shows all students for a given site, the days when school was in session for this month (not Saturday, Sunday) and a X for the student who participated in that day or a null value if they do not have.

    ID # FNAME LNAME 3 4 5 6 7 10
    38754636 POE JANE X X X
    81248754 DOE KAYLA X X X X X
    43127409 RAO JOHN X X X X X

    In this example, days 3 and 7 of the month are from Monday to Friday and 8-9 have been excluded because they are on Saturday and Sunday.

    I am trying to find a way to dynamically generate a query for any month/year and returning to a report. The obstacle is that given that I don't know in advance which days in a month will be excluded, the identifiers in my select statement are not fixed.

    I found a query that returns a list of day numbers and dates for a given month. It looks like this:

    SELECT LEVEL lv, TO_DATE (TO_CHAR (LEVEL, '09')
    || TO_CHAR (EXTRACT (TO_DATE('01-SEP-11') MONTHS), '09')
    || To_char (EXTRACT (TO_DATE('01-SEP-11') YEAR), ' 9999'), 'dd.mm.yyyy') mon_day
    OF double WHERE ROWNUM < = EXTRACT (DAY OF LAST_DAY (TO_DATE('01-SEP-11')))
    CONNECT BY LEVEL = ROWNUM

    I combined this request with another brings my student attendance data and results that pivots in what I need. Then, I created a function that accepts the month and year as parameters and creates the combined request.

    SELECT c.ID student_id, c.last_name, c.first_name,.
    MAX (decode (mon_day, ' 01 - SEPT.-11', 'X', NULL)) '1', MAX (decode (mon_day, ' 02 - SEVEN.-11', 'X', NULL)) '2 ',.
    MAX (decode (mon_day, ' 05 - SEPT.-11', 'X', NULL)) '5', MAX (decode (mon_day, ' 06 - SEPT.-11', 'X', NULL)) "6."
    MAX (decode (mon_day, ' 07-SEP-11', 'X', NULL)) '7', MAX (decode (mon_day, ' 08 - SEPT.-11', 'X', NULL)) "8."
    MAX (decode (mon_day, ' 09 - SEPT.-11', 'X', NULL)) '9', MAX (decode (mon_day, 12-SEP-11', 'X', NULL)) "12."
    MAX (decode (mon_day, 13-SEP-11', 'X', NULL)) '13', MAX (decode (mon_day, 14-SEPT-11', 'X', NULL)) "14."
    MAX (decode (mon_day, 15-SEP-11', 'X', NULL)) '15', MAX (decode (mon_day, 16-SEP-11', 'X', NULL)) "16."
    MAX (decode (mon_day, 19-SEP-11', 'X', NULL)) '19', MAX (decode (mon_day, 20-7.-11', 'X', NULL)) "20."
    MAX (decode (mon_day, 21-SEP-11', 'X', NULL)) "21", MAX (decode (mon_day, 22-SEP-11', 'X', NULL)) '22 ',.
    MAX (decode (mon_day, 23-SEP-11', 'X', NULL)) '23', MAX (decode (mon_day, 26-SEP-11', 'X', NULL)) "26."
    MAX (decode (mon_day, 27-SEP-11', 'X', NULL)) '27', MAX (decode (mon_day, 28-SEP-11', 'X', NULL)) "28."
    MAX (decode (mon_day, 29-SEP-11', 'X', NULL)) '29', MAX (decode (mon_day, 30-SEP-11', 'X', NULL)) '30 '.
    (SELECT level lv, TO_DATE (TO_CHAR (LEVEL, '09')
    || TO_CHAR (EXTRACT (TO_DATE('01-SEP-11') MONTHS), '09')
    || To_char (EXTRACT (TO_DATE('01-SEP-11') YEAR), ' 9999'), 'dd.mm.yyyy') mon_day
    OF double WHERE ROWNUM < = EXTRACT (DAY OF LAST_DAY (TO_DATE('01-SEP-11')))
    CONNECTION LEVEL = ROWNUM) a, b of attendance, student c
    WHERE to_char(MON_DAY,'D') NOT IN (1.7)
    AND A.mon_day = b.attendance_date
    AND b.student_id = c.ID
    Group of c.ID, student_id, c.last_name, c.first_name

    Now I'm stuck on what I can pass this request in to get my result. What I've read, dynamic SQL method 4 would work if I incorporate Pro/C. I hope this isn't my only option. I have considered to try to do this in a function table in pipeline, but since the columns returned are not known in advance, I can't create a corresponding data type.

    I'm starting to wonder if I forgot a simpler method to achieve this.

    Published by: David Sumner on April 12, 2012 18:52

    Ignoring the actual query and looking at the dynamic SQL part of the question.

    There are 3 ways to run a dynamic select SQL in PL/SQL code.

    immediate execution requires a fixed number of bind variables, linking him in position and translates a single implicit output cursor extraction - requiring the projection of cursor to be known at the time of coding.

    REF CURSOR are essentially the same - the only exception being that it requires an extraction explicit coding process output cursor.

    DBMS_SQL differs in all of these respects. The connection is by name and not position. The connection is dynamic. Projection of the cursor must not be known at the time of coding. It is dynamically determined at runtime and fetch offers of release of the cursor with the projection of unknown SQL - coding time.

    Apex uses DBMS_SQL internally (in fact he uses DBMS_SYS_SQL properly run dynamic and specific patterns of Oracle SQL, as if a session connected as a scheme runs the SQL code). This allows the Apex to take a dynamic SQL that you enter a region (which can contain a variable number of bind variable), run it and make the projection of the cursor as an HTML report.

    Apex supports in turn also dynamic SQL - what you (Apex developer) to provide a dynamic SQL code for a region, instead of you having to provide SQL fixed (with bind variable) for the region in question.

    As Apex creates DBMS_SQL sliders, it doesn't have your SQL as a ref cursor or cursor DBMS_SQL. All they need is the source of the SQL statement. And that's what you create dynamically.

    So in the Apex, dynamic SQL means using a function from PL/SQL to return the source for Apex SQL analyze like a slider DBMS_SQL - instead of coding the source SQL statement in a fixed statement.

    So, using the option of function for an area considered in the Apex, allows you to provide the following in the code that must run to get the SQL statement for the report Apex (Apex running this as a dynamic function that returns a string):

    --// return the dynamic SQL for the report region
    return(
      case
        when :P1_OPTION = 1 then
          'select * from emp'
    
        when :P1_OPTION = 2 then
          'select * from dept where dept_id = :P1_DEPT_ID'
      end
    );
    

    You can also write a PL/SQL function that is stored in the database and call this function so that it can determine what is the dynamic SQL source code statement. For example

    --// calling database function to return the dynamic SQL for the report region
    return(
      GetDynamicReportSQL( page => 1, option => :P1_OPTION )
    );
    

    Dynamic SQL is fully supported by Apex - but does not require that you, the developer, to create the dynamic cursor and treat the dynamic linking and dynamic recovery of this slider.

    All you have to do is to provide the source code of this dynamic SQL (including the bind variable) to the Apex and it will do the whole thing from cursor for you.

  • Help with dynamic SQL

    Hello

    I have the following function that works well:

    FUNCTION to CREATE or REPLACE Get_Partition_Name (sTable VARCHAR2, iImportIndex INTEGER)
    RETURN VARCHAR2 IS

    cursor c is select A.partition_name from (select table_name, nom_partition,
    ExtractValue)
    dbms_xmlgen.
    () getxmltype
    "Select high_value of all_tab_partitions where table_name =" '. "
    || table-name
    || ' ' and table_owner = "'
    || TABLE_OWNER
    || ' ' and nom_partition = "'
    || nom_partition
    || ''''),
    import_value of all_tab_partitions) where table_name sTable = and A.import_value = iImportIndex;
    sPartitionName varchar (20);
    err_num NUMBER;

    BEGIN
    Open c;
    extract the c in sPartitionName;

    IF c % ISOPEN THEN
    C CLOSE;
    END IF;

    RETURN sPartitionName;

    EXCEPTION
    WHILE OTHERS THEN
    err_num: = SQLCODE;
    -Save the error in the log table
    NEWSPAPER. SAVELINE (SQLCODE, SQLERRM);
    END Get_Partition_Name;

    I am trying to replace the dynamic SQL, something like cursor statement (see below), but it's broken. According to me, Miss me some quotes.

    FUNCTION to CREATE or REPLACE Get_Partition_Name (sTable VARCHAR2, iImportIndex INTEGER)
    RETURN VARCHAR2 IS
    TYPE t1 IS REF CURSOR;
    c t1;
    sSql VARCHAR2 (500);
    sPartitionName varchar (20);
    err_num NUMBER;

    BEGIN
    sSql: = ' select A.partition_name from (select table_name, nom_partition,
    ExtractValue)
    dbms_xmlgen.
    () getxmltype
    'select high_value of all_tab_partitions where table_name ="'
    || table-name
    || ' ' and table_owner = "'
    || TABLE_OWNER
    || ' ' and nom_partition = "'
    || nom_partition
    || ''''''),
    text() ") import_value of all_tab_partitions) where table_name =: a and A.import_value =: b';

    C OPEN sSql USING sTable, iImportIndex;
    extract the c in sPartitionName;

    IF c % ISOPEN THEN
    C CLOSE;
    END IF;

    RETURN sPartitionName;

    EXCEPTION
    WHILE OTHERS THEN
    err_num: = SQLCODE;
    -Save the error in the log table
    NEWSPAPER. SAVELINE (SQLCODE, SQLERRM);
    END Get_Partition_Name;
    /

    Please advise,

    Kind regards
    M.R.

    Assuming that the requirement is to find the partition in the table provided with the provided high value and the problem is that dba/all_tab_partitions.high_value is of type long, an alternative solution in the same sense that you already made is as follows. (I just used a slider instead of a function for the simplicity of the demo).

    SQL> var r refcursor
    SQL> set autoprint on
    SQL> declare
      2   ctx dbms_xmlgen.ctxhandle;
      3   v_table_name VARCHAR2(40) := 'LOGMNR_USER$';
      4   v_value      NUMBER       := 100;
      5  begin
      6   ctx := DBMS_XMLGEN.NEWCONTEXT
      7          ('select table_name
      8            ,      partition_name
      9            ,      high_value  hi_val
     10            from   dba_tab_partitions
     11            where  table_name     = :table_name');
     12   dbms_xmlgen.setbindvalue(ctx,'TABLE_NAME',v_table_name);
     13   open:r for
     14   with x as
     15   (select xmltype(dbms_xmlgen.getxml(ctx)) myxml
     16    from   dual)
     17   select extractvalue(x.object_value,'/ROW/TABLE_NAME') table_name
     18   ,      extractvalue(x.object_value,'/ROW/PARTITION_NAME') partition_name
     19   ,      extractvalue(x.object_value,'/ROW/HI_VAL') hi_val
     20   from   x
     21   ,      TABLE(XMLSEQUENCE(EXTRACT(x.myxml,'/ROWSET/ROW'))) x
     22   where  extractvalue(x.object_value,'/ROW/HI_VAL') = v_value;
     23  end;
     24  /
    
    PL/SQL procedure successfully completed.
    
    TABLE_NAME
    -------------------------------------------------------------------------------
    PARTITION_NAME
    -------------------------------------------------------------------------------
    HI_VAL
    -------------------------------------------------------------------------------
    LOGMNR_USER$
    P_LESSTHAN100
    100
    
    SQL> 
    

    I don't know that there are other ways as well. Especially with the XML features, there are normally several ways to skin a cat.

  • String with dynamic SQL in APEX

    Hello

    I need assistance with dynamic SQL new... sigh...

    Could someone post Oracle rules use for the string of quoted text in the dynamic SQL statements?

    How to encode the following SQL statement in dynamic SQL?

    Select * from emp where State in ('CA', 'HI')

    declare
    l_sql varchar2 (400)
    Start
    l_sql: = ' select * from emp where indicate in ("' CA" '...)
    end;

    Please provide coding rules... Thank you very much

    Chris :)

    Hello

    Two single quotes will be replaced by a single quotation mark when used in a string. So:

    declare
    l_sql varchar2(400)
    begin
    l_sql := 'select * from emp where state in (''CA'' .....
    end;
    

    If you need to close the string to be concatenated to another channel, then you use an other single quotation mark to close the chain and open it again later:

    declare
    l_sql varchar2(400)
    begin
    l_sql := 'select * from emp where state in (''' || a_string_variable || ''' .....
    end;
    

    Andy

  • How the date can be filled with timestamp in dynamic sql

    Hi all

    Below we have sql

    v_stmt: = ' MERGE IN MTH_EQUIPMENTS_EXT_B ED

    WITH THE HELP OF)

    SELECT TAG_DATA,

    EQUIPMENT_FK_KEY,

    WORKORDER_FK_KEY,

    SEGMENT_FK_KEY,

    SHIFT_WORKDAY_FK_KEY,

    HOUR_FK_KEY,

    ITEM_FK_KEY,

    READ_TIME,

    ATTR_GROUP_ID,

    RECIPE_NUM,

    RECIPE_VERSION,

    NVL (FND_GLOBAL. User_Id,-1) l_updated_by,.

    NVL (FND_GLOBAL. Login_Id,-1) l_last_update_login

    OF MTH_TAG_READINGS_T_STG

    WHERE DB_COL = ' | " ' || v_colname | " ' ||') TS

    WE (';)

    v_stmt: = v_stmt | "ED. EQUIPMENT_PK_KEY = TS. EQUIPMENT_FK_KEY AND

    ED. READ_TIME = TS. READ_TIME AND

    ED. ATTR_GROUP_ID = TS. ATTR_GROUP_ID)

    WHEN MATCHED THEN

    UPDATE

    GAME ED.'. v_colname |' = TS. TAG_DATA,

    ED. LAST_UPDATED_BY = 1, ";

    v_stmt: = v_stmt | "ED. LAST_UPDATE_LOGIN = TS.l_last_update_login

    WHEN NOT MATCHED THEN

    INSERT ('| v_colname |', EXTENSION_ID, EQUIPMENT_PK_KEY, WORKORDER_FK_KEY, SEGMENT_FK_KEY, SHIFT_WORKDAY_FK_KEY, HOUR_FK_KEY, ITEM_FK_KEY, READ_TIME, ATTR_GROUP_ID, LAST_UPDATE_DATE, LAST_UPDATED_BY,';)

    v_stmt: =.

    v_stmt | ("LAST_UPDATE_LOGIN, CREATED_BY, CREATION_DATE, RECIPE_NUM, RECIPE_VERSION)

    VALUES (TS. TAG_DATA, EGO_EXTFWK_S.NEXTVAL, TS. EQUIPMENT_FK_KEY, TS. WORKORDER_FK_KEY, TS. SEGMENT_FK_KEY, TS. SHIFT_WORKDAY_FK_KEY, TS. HOUR_FK_KEY, TS. ITEM_FK_KEY, TS. READ_TIME,';

    v_stmt: = v_stmt | "TS. ATTR_GROUP_ID,' | '''|| SYSDATE | "'| ', 1, TS.l_last_update_login, TS.l_updated_by,'|"' | SYSDATE | " ' ||', TS. RECIPE_NUM, TS. RECIPE_VERSION)';

    EXECUTE IMMEDIATE v_stmt;

    After you run the above SQL last date of update in MTH_EQUIPMENST_EXT_B is filled with sysdate but timestamp is not its always 00:00:00. Can we have timestamp also populated through dynamic sql in the last update date

    Kind regards

    Amrit

    Values to hardcode in the dynamic SQL - never use bind variables:

    v_stmt: = ' MERGE IN MTH_EQUIPMENTS_EXT_B ED

    WITH THE HELP OF)

    SELECT TAG_DATA,

    EQUIPMENT_FK_KEY,

    WORKORDER_FK_KEY,

    SEGMENT_FK_KEY,

    SHIFT_WORKDAY_FK_KEY,

    HOUR_FK_KEY,

    ITEM_FK_KEY,

    READ_TIME,

    ATTR_GROUP_ID,

    RECIPE_NUM,

    RECIPE_VERSION,

    NVL (FND_GLOBAL. User_Id,-1) l_updated_by,.

    NVL (FND_GLOBAL. Login_Id,-1) l_last_update_login

    OF MTH_TAG_READINGS_T_STG

    WHERE DB_COL =: 1) TS

    WE (';)

    v_stmt: = v_stmt | "ED. EQUIPMENT_PK_KEY = TS. EQUIPMENT_FK_KEY AND

    ED. READ_TIME = TS. READ_TIME AND

    ED. ATTR_GROUP_ID = TS. ATTR_GROUP_ID)

    WHEN MATCHED THEN

    UPDATE

    GAME ED.'. v_colname |' = TS. TAG_DATA,

    ED. LAST_UPDATED_BY = 1, ";

    v_stmt: = v_stmt | "ED. LAST_UPDATE_LOGIN = TS.l_last_update_login

    WHEN NOT MATCHED THEN

    INSERT ('| v_colname |', EXTENSION_ID, EQUIPMENT_PK_KEY, WORKORDER_FK_KEY, SEGMENT_FK_KEY, SHIFT_WORKDAY_FK_KEY, HOUR_FK_KEY, ITEM_FK_KEY, READ_TIME, ATTR_GROUP_ID, LAST_UPDATE_DATE, LAST_UPDATED_BY,';)

    v_stmt: =.

    v_stmt | ("LAST_UPDATE_LOGIN, CREATED_BY, CREATION_DATE, RECIPE_NUM, RECIPE_VERSION)

    VALUES (TS. TAG_DATA, EGO_EXTFWK_S.NEXTVAL, TS. EQUIPMENT_FK_KEY, TS. WORKORDER_FK_KEY, TS. SEGMENT_FK_KEY, TS. SHIFT_WORKDAY_FK_KEY, TS. HOUR_FK_KEY, TS. ITEM_FK_KEY, TS. READ_TIME,';

    v_stmt: = v_stmt | "TS. ATTR_GROUP_ID,: 2, 1, TS.l_last_update_login, TS.l_updated_by,: 3, TS. RECIPE_NUM, TS. RECIPE_VERSION)';

    V_stmt EXECUTE IMMEDIATE

    With the HELP of v_colname,.

    SYSDATE,

    SYSDATE;

    SY.

  • Dynamic processing of single quotes in SQL

    Version: 11.2.0.4

    I'm kinda a beginner when it comes to dynamic SQL.

    I had a condition in which I had to run the following command on all the data files in the DB.

    -Expected results

    change datafile resizing '< Filename >' database 10g;

    The name of file, which is generated dynamically must be in single quotes.

    -Sample data

    create table x (file_name varchar2 (90));

    Insert into x values ('/ u04/oradata/ORCL/system.dbf');

    Insert into x values ('/ u04/oradata/ORCL/sysaux.dbf');

    Insert into x values ('/ u04/oradata/ORCL/users01.dbf');

    I managed to do it using a similair below code. But I had to do several things of trial and error to get this working in reason to get the correct number of single quotes for the string generated for v_sql below. So, I want to rethink the basics.

    declare

    v_sql varchar2 (350);

    Start

    for rec in (select x file_name)

    loop

    v_sql: = "alter database datafile"'| " Rec.file_name | " 'resize 10g;

    -RUN IMMEDIATELY v_sql;

    dbms_output.put_line (v_sql);

    end loop;

    end;

    /

    ALTER database datafile ' / u04/oradata/ORCL/system.dbf' size 10g

    ALTER database datafile ' / u04/oradata/ORCL/sysaux.dbf' size 10g

    ALTER database datafile ' / u04/oradata/ORCL/users01.dbf' size 10g

    PL/SQL procedure successfully completed.

    I would like to know the role played by each single quote. I used 8 apostrophes in the V_SQL variable above, and I numbered each single quotation mark as shown below.

    1                        234                 567           8

    |                        |||                 |||           |

    v_sql: = "alter database datafile"'| " Rec.file_name | " 'resize 10g;

    Example of output from the generation of dynamic channels:

    alter database datafile '/u04/oradata/ORCL/users01.dbf' 10g resizing

    1 and 4-> start and end of the string alter database datafile '

    3 > literal single quote of string in red in the example output

    2 > escape 3 (single literal quote of string)

    5 and 8-> start and end of the string ' resize 10 g

    6-> escape 7 (single literal quote of string)

    7 > literal single quote of string in green in the example output

    My asssumptions are correct?

    I would like to write like this.

    declare
       v_sql    varchar2(350);
    begin
      for rec in (select file_name from x)
          loop
            v_sql := q'[alter database datafile '#FILENAME#' resize 10g]';
            v_sql := replace(v_sql, '#FILENAME#', rec.file_name);
            --- EXECUTE IMMEDIATE v_sql;
            dbms_output.put_line ( v_sql);
        end loop;
    end;
    /
    
  • Several SQL statements with zero executions in the region of SQL

    Hello

    one of my databases has a large number of statements in the SQL box with zero executions. Some of them analyzed several times without a single run. Why the database stores these statements and how to avoid or reduce them?

    My problem is that the only time or zero time sql statements take the largest part of the area of sql:

    -sql statement and only once and without executing sql statements

    Select

    Count (1) num_sql_total,.

    sum (decode (executions, 1, 1, 0)) num_one_use_sql,.

    sum (decode (executions, 0, 1, 0)) num_no_use_sql,.

    Sum (RUNTIME_MEM) / 1024/1024 mb_used,.

    sum (decode (executions, sharable_mem, 1, 0)) / 1024/1024 mb_for_one_use_sql,.

    sum (decode (executions, 0, sharable_mem, 0)) / 1024/1024 mb_for_no_use_sql

    Of

    GV$ sqlarea

    where

    RUNTIME_MEM > 0;

    NUM_SQL_TOTAL NUM_ONE_USE_SQL NUM_NO_USE_SQL MB_USED MB_FOR_ONE_USE_SQL MB_FOR_NO_USE_SQL

    23318

    8739

    8027

    1420,95619106293

    381,41183757782

    530,999855041504

    Concerning

    Thomas

    This is not unusual. Another app could analyze for example hard the most often used SQLs in upstairs app - making benefit of further processing (in theory) of sweet analysis when you use these SQLs.

    In fact, I remember reading something to this effect as a performance for some factor or another Oracle document or note?

    So unless you have serious questions of shared pool, why bother with these sliders? What would be the problem?

  • Works with dynamic sql and list of numbers as return value

    Hello.

    Problems:

    1. How can I insert the USERNAME variable in the string so it will be replaced over time.
    2. I intend to return a list of IDS as 1,4,6,7,2 I want to use later in an IN clause.

    How to complete the return function with the dynamic sql output variable?
    I have no preference to dynamic sql but it was just something that came into my mind
    When I thought that the implementation of the obligation to choose a list of offices for specific user groups.
    (select statements from the sample are cut short, they're actually really big and I want to reuse this function in my)
    BI Publisher data model for multiple modells).


    CREATE or REPLACE FUNCTION F_OFFICES (-input parameters)
    USERNAME IN VARCHAR2
    USERGROUP IN VARCHAR2,
    )
    -Output parameter
    RETURN VARCHAR2 AS
    dynSQL VARCHAR2 (1000);
    BEGIN

    IF USERGROUP = "local" THEN

    dynSQL: = 'xxx SELECT FROM CO_B WHERE Userid = username';

    ELSIF USERGROUP = "regional" THEN

    dynSQL: = "SELECT...". » ;

    ELSIF USERGROUP 'federal' = THEN
    dynSQL: = "SELECT...". » ;

    END IF;

    EXECUTE IMMEDIATE dynSQL;

    -RETURN?;

    END F_OFFICES;


    Thanks for any help.

    As you have presented essentially pseudo-code we can only give you a Pseudo-solution :)

    But the principle is:

    ...
    --Output parameter
    RETURN VARCHAR2 AS
        dynSQL VARCHAR2(1000);
        return_value varchar2(30):
    BEGIN
    
      IF USERGROUP = 'local' THEN
        dynSQL:= 'SELECT xxx FROM CO_B WHERE userid = :1'; -- placeholder for parameter
    
       ...
      END IF;
    
      EXECUTE IMMEDIATE dynSQL
         using USERNAME -- pass parameters in placeholder order
         into return_value;   -- obviously this must match the projection of the dynamic query 
    
      RETURN return_value; 
    
    END F_OFFICES ;
    

    This approach is not good if you want to vary the dynamic query projection. In this case, you can use a REF CURSOR or maybe DBMS_SQL.

    Cheers, APC

  • How to use Bulk collect in dynamic SQL with the example below:

    My Question is

    Using of dynamic SQL with collection in bulkif we pass the name of the table as "to the parameter' function, I want to display those

    An array of column names without vowels (replace the vowels by spaces or remove vowels and display).

    Please explain for example.

    Thank you!!

    It's just a predefined type

    SQL> desc sys.OdciVarchar2List
     sys.OdciVarchar2List VARRAY(32767) OF VARCHAR2(4000)
    

    You can just as easily declare your own collection type (and you are probably better served declaring your own type of readability if nothing else)

    SQL> ed
    Wrote file afiedt.buf
    
      1  CREATE OR REPLACE
      2     PROCEDURE TBL_COLS_NO_VOWELS(
      3                                  p_owner VARCHAR2,
      4                                  p_tbl   VARCHAR2
      5                                 )
      6  IS
      7     TYPE vc2_tbl IS TABLE OF varchar2(4000);
      8     v_col_list vc2_tbl ;
      9  BEGIN
     10      EXECUTE IMMEDIATE 'SELECT COLUMN_NAME FROM DBA_TAB_COLUMNS WHERE OWNER = :1 AND TABLE_NAME = :2 ORDER BY COLUMN_ID'
     11         BULK COLLECT
     12         INTO v_col_list
     13        USING p_owner,
     14              p_tbl;
     15      FOR v_i IN 1..v_col_list.COUNT LOOP
     16        DBMS_OUTPUT.PUT_LINE(TRANSLATE(v_col_list(v_i),'1AEIOU','1'));
     17      END LOOP;
     18*  END;
    SQL> /
    
    Procedure created.
    
    SQL> exec tbl_cols_no_vowels( 'SCOTT', 'EMP' );
    MPN
    NM
    JB
    MGR
    HRDT
    SL
    CMM
    DPTN
    
    PL/SQL procedure successfully completed.
    

    Justin

  • Dynamic SQL with in bulk in the record type

    Oracle 10.2 g

    I received this Tom

    [http://asktom.oracle.com/pls/apex/f?p=100:11:0:NO:]

    I'm able to do this without dynamic SQL, but my requirement is to do it in dynamic SQL
     create table t1 ( x int, y int );
    
     insert into t1 select rownum, rownum+1 from all_users where rownum <= 5;
    
     create table t2 ( x int, y int, z int );
    
     declare
                type array is table of t1%rowtype;
                l_data array;
        begin
                select * bulk collect into l_data from t1;
      
                forall i in 1 .. l_data.count
                
                       execute immediate 'insert into (select x, y from t2) values :x' using l_data(i);
        end;
     
    Error at line 1
    ORA-06550: line 9, column 90:
    PLS-00457: expressions have to be of SQL types
    ORA-06550: line 9, column 20:
    PL/SQL: Statement ignored
    There is a work around in 11g, but can we do something in 10g?



    Thank you
    HESH.

    HESH wrote:

    but following does not.

    declare
    type array is table of t1%rowtype;
    l_data array;
    begin
    select * bulk collect into l_data from t1;
    
    forall i in 1 .. l_data.count
    
    execute immediate 'insert into (select x, y from t2) values :x' using l_data(i);
    end;
    

    I want just a dynamic SQL code for the insert with FORALL statement would adopt as well as collections.

    Doesn't make much sense.

    Extract you the data from the SQL engine in the table of the record type. If the output data that cursor SQL must be read in the SQL engine and copied into the memory of PL/SQL engine.

    Then, you send that VERY SAME DATA back to the SQL engine to be used by a SQL insert cursor.

    Where is the logic behind the extraction of data from SQL in a PL/SQL table structure and then push this same structure table on the SQL engine database? What is the purpose to send data on a detour of underperforming and non-scalale through the PL/SQL engine?

    You have any justification (technical or functional wise) to back up this absurd approach?

    Why this can be achieved using a single SQL cursor that does both the choice (extraction) and (in bulk) insertion - using the plain old INSERT... SELECT structure?

    And if the insert is variable, then what? Create a dynamic INSERT... SELECT cursor and execute it (using bind values). This simple... Right?

  • FORALL with dynamic SQL

    Hello people,

    I'm just wondering that when you want to handle the large amount of lines we use FORALL to reduce the change of context. So, what happens if when we use dynamic sql instead of normal SQL FORALL. I mean using the dynamic SQL inside FORALL increase performance?

    Because I know that when we use the variable binding in sql statements or questions, then it will scan only just 1 hour instead of every time. Therefore, other SQL statements don't need to analyze which does not have a performance gain?

    FORALL reduced context switching AND SQL dynamic with bind variable prevent unnecessarily analysis, so wheren here are using hear, she will be better performance isn't? Please correct me if I'm wrong.

    For example;
    FORALL i IN l_in_tab.first .. l_in_tab.last
        EXECUTE IMMEDIATE
          'DELETE FROM bulk_collect_test
           WHERE  object_id = :1'
           USING l_in_tab(i);
    Thank you very much.

    >
    Dynamic SQL with variable bind unnecessarily prevent analysis
    >
    Yes - compared to dynamic SQL that does not bind variable.

    Just use

    DELETE FROM bulk_collect_test
           WHERE  object_id = l_in_tab(i);
    

    FORALL essentially uses a form of BONDING in BULK already

    See reduction in overhead costs of loop for DML statements and queries with SQL in bulk in Chapter 12 Applications of PL/SQL Tuning of Performance in the PL/SQL doc
    http://docs.Oracle.com/CD/B28359_01/AppDev.111/b28370/tuning.htm#sthref1455

    >
    Bulk SQL uses PL/SQL collections to pass back and forth large quantities of data in simple operations. This process is called binding of bulk. If the collection has n elements, bulk binding uses a single operation to perform the equivalent of n SELECT INTO, INSERT, UPDATE, or DELETE statements

  • Tables created in a stored procedure cannot be used with dynamic SQL? The impact?

    There is a thread on the forum which explains how to create tables within a stored procedure (How to create a table in a stored procedure , however, it does create a table as such, but not how to use it (insert, select, update, etc.) the table in the stored procedure.) Looking around and in the light of the tests, it seems that you need to use dynamic SQL statements to execute ddl in a stored procedure in Oracle DB. In addition, it also seems that you cannot use dynamic SQL statements for reuse (insert, select, update, etc.) the table that was created in the stored procedure? Is this really the case?

    If this is the case, I am afraid that if tables cannot be 'created and used"in a stored procedure using the dynamic SQL, as is the case with most of the servers of DB dynamic SQL is not a part of the implementation plan and, therefore, is quite expensive (slow). This is the case with Oracle, and if yes what is the performance impact? (Apparently, with Informix, yield loss is about 3 - 4 times, MS SQL - 4 - 5 times and so on).

    In summary, tables created within a stored procedure cannot be 'used' with dynamic SQL, and if so, what is the impact of performance as such?

    Thank you and best regards,
    Amedeo.

    Published by: AGF on March 17, 2009 10:51

    AGF says:
    Hi, Frank.

    Thank you for your response. I understand that the dynamic SQL is required in this context.

    Unfortunately, I am yet to discover "that seeks to" using temporary tables inside stored procedures. I'm helping a migration from MySQL to Oracle DB, and this was one of the dilemmas encountered. I'll post what is the attempt, when more.

    In Oracle, we use [global temporary Tables | http://www.psoug.org/reference/OLD/gtt.html?PHPSESSID=67b3adaeaf970906c5e037b23ed380c2] aka TWG these tables need only be created once everything like a normal table, but they act differently when they are used. The data inserted in TWG will be visible at the session that inserted data, allowing you to use the table for their own temporary needs while not collide with them of all sessions. The data of the TWG will be automatically deleted (if not deleted programmatically) when a) a commit is issued or b) the session ends according to the parameter that is used during the creation of the TWG. There is no real need in Oracle to create tables dynamically in code.

    I noticed that many people say that the "Creation of the tables within a stored procedure" is not a good idea, but nobody seems necessarily explain why? Think you could elaborate a little bit? Would be appreciated.

    The main reason is that when you come to compile PL/SQL code on the database, all explicit references to tables in the code must correspond to an existing table, otherwise a djab error will occur. This is necessary so that Oracle can validate the columns that are referenced, the data types of those columns etc.. These compilation controls are an important element to ensure that the compiled code is as error free as possible (there is no accounting for the logic of programmers though ;)).

    If you start to create tables dynamically in your PL/SQL code, so any time you want to reference this table you must ensure that you write your SQL queries dynamically too. Once you start doing this, then Oracle will not be able to validate your SQL syntax, check the types of data or SQL logic. This makes your code more difficult to write and harder to debug, because inevitably it contains errors. It also means that for example if you want to write a simple query to get that one out in a variable value (which would take a single line of SQL with static tables), you end up writing a dynamic slider all for her. Very heavy and very messy. You also get the situation in which, if you create tables dynamically in the code, you are also likely to drop tables dynamically in code. If it is a fixed table name, then in an environment multi-user, you get in a mess well when different user sessions are trying to determine if the table exists already or is the last one to use so they can drop etc. What headache! If you create tables with table names, then variable Dynamics not only make you a lot end up creating (and falling) of objects on the database, which can cause an overload on the update of the data dictionary, but how can ensure you that you clean the tables, if your code has an exception any. Indeed, you'll find yourself with redundant tables lying around on your database, may contain sensitive data that should be removed.

    With the TWG, you have none of these issues.

    Also, what is the impact on the performance of the dynamic SQL statements in Oracle? I read some contrasting opinions, some indicating that it is not a lot of difference between static SQL and SQL dynamic in more recent versions of Oracle DB (Re: why dynamic sql is slower than static sql is this true?)

    When the query runs on the database, there will be no difference in performance because it is just a request for enforcement in the SQL engine. Performance problems may occur if your dynamic query is not binding variable in the query correctly (because this would cause difficult analysis of the query rather than sweet), and also the extra time, to dynamically write the query running.

    Another risk of dynamic query is SQL injection which may result in a security risk on the database.

    Good programming will have little need for the tables of dynamically created dynamically or SQL.

Maybe you are looking for

  • Satellite A30-921 - specification of the processor?

    I have really bad bent pins on my CPU and I need to buy a new one. What processor the laptop uses by default, so I don't know what to buy. Thank you.

  • Pavilion dv3500 - FZ941PA #ABG: time Internet will not sync automatically

    Hello! Good day again! My time Internet is not synchronized automatically, so in everyday life I always synchronize it manually, I follow some sites about procedures, they synchronize but not automatically and also in the registry, I try to change it

  • HP Mini 110: Password for the BIOS of HP Mini reset

    I need help... This HP Mini 110 somehow now need a startup password in the system BIOS. I had an idea what it would be: HP Mini 110 Series # [personal information] As soon as I boot it asks me enter CURRENT password: After the third time I get: Passw

  • simulation does not work

    I composed a few diodes the wizard of components, such as the diode acts like a switch perfect to 0.7 volts.  For some reason any SPICE simulation does not run.   If I include one of these diodes in other circuits, the circuit will not simulate.  The

  • BlackBerry Smartphones double payment posted

    I just bought app on my torch battery saver 9860 through my credit card from a value of rs. 100 Indian rupees. And I had to add my credit card details in the blackberry world for this purpose, my problem is that there are two amounts deducted 103 and