problem using dynamic sql

Hi all

I have to insert the record in a table in one database to another database which requires db_link.so to do this I use run immediately, but when I try to insert by using the procedure below it will directly itno exception block.
Help, please



declare
p_study_to NUMBER: = 1;
p_study_from NUMBER: = 3;
P_db_link VARCHAR2 (30): = 'abc ';
BEGIN

RUN IMMEDIATELY ' INSERT INTO RRRRR
(study_to, db_link, dt_created, dt_modified, modified_by)'
||' SELECT study_to, db_link, dt_created,
dt_modified, modified_by
OF UUUU@:2'
using p_study_to, p_db_link;
EXCEPTION
WHILE OTHERS
THEN
dbms_output.put_line ('error when inserting in RRRRR');
END;
/


Thanks in advance!

Hello

You can tell only AID like this to give values for expressions, not table names (or their qualifications, as in this case).
Try:

declare
     p_study_to     NUMBER := 1;
     p_study_from      NUMBER := 3;
     P_db_link      VARCHAR2(30) := 'abc';
     sql_txt          VARCHAR2 (2000);
BEGIN

     sql_txt := 'INSERT INTO     RRRRR (study_to, db_link, dt_created, dt_modified, modified_by)'
          ||           ' SELECT  study_to, db_link, dt_created, dt_modified, modified_by'
          ||          ' FROM    UUUU@' || p_db_link ;
     dbms_output.put_line (sql_txt);

        -- EXECUTE IMMEDIATE  sql_txt;
END;

Whenever you write dynamic sql code, it displays first.
Only when it shows something that looks right should you UN-comment the EXECUTE IMMEDIATE statement.
Before you go into Production, comment out code (or delete) the call to put_line.

Use an EXCEPTION handler only when you can improve on what is the mechanism of error by default, for example, you plan a particular error, and you have something specail do when this error occurs.

Using dynamic SQL just to have the same code running on different databases, where each database needs a different connection name? If so, use synonyms instead of dynamic SQL.

Tags: Database

Similar Questions

  • link: new values on after the trigger by using dynamic sql.

    Hello all I have a problem I want to solve using dynamic sql on a trigger. The problem is that are around 5 qty fields who each have 18 separate fields. This is because of different sizes (S, M, L, XL, etc., up to 18). So I will try to use the: new values on a trigger to dynamically fill these information on a table, but immediate execution is run is returning the value like: new.open_sz (x) instead of the actual numeric value of the column. See code below. Is there a way to do this.

    Thank you in advance.


    CREATE OR REPLACE TRIGGER T_EXAMPLE
    after update of
    open_sz1, open_sz2, open_sz3, open_sz4, open_sz5, open_sz6,
    open_sz7, open_sz8, open_sz9, open_sz10, open_sz11, open_sz12,
    open_sz13, open_sz14, open_sz15, open_sz16, open_sz17, open_sz18
    on order_li_m for each line
    declare
    Is of TYPE NumArray table indexes number directory;
    NumArray v_orderqty;
    -TYPE VarArray is the table of the varchar2 (200) index directory.
    -v_orderqty K_A2KSTD. VarArray;
    v_col varchar2 (30);
    v_sql varchar2 (1000);
    BEGIN
    for a 1 in... 18 loop
    v_col: = ': new.open_sz' | one;
    v_sql: = ' SELECT: 1 double ';
    run immediately v_sql in v_orderqty (a) using v_col;
    dbms_output.put_line (v_orderqty (a));
    end loop;
    end T_EXAMPLE;
    /

    Raffy Martin wrote:
    Is there a way to do this.

    You may not use: news and: old identifiers in dynamic SQL, the way to do it is to specify the real column names.

  • How to write the SQL without using dynamic SQL?

    How can you write this under SQL without using execute immediately?

    You can use static SQL (using something like a CASE statement)?

    test procedure (one in varchar2, b number, each number) is

    v_num_recs pls_integer;

    Start

    Select count (*)

    in v_num

    FROM table1

    where

    col1 = one and

    If b is not null then col2 = b

    If c is not null then col3 = c;

    / * i.e. If b is not null, where condition to add this line only. If c is not null, where condition should add only this line. OR condition No. it * /.

    dbms_output.put_line (v_num);

    end;

    Or should I use dynamic SQL statements for this?

    I was wondering if the two are NOT NULL? Well check this.

    Select count (*) in v_num

    table

    where col1 = one

    and col2 = (CASE WHEN (b is not null) THEN b ELSE END col2)

    and col3 = (CASE WHEN (c is not null) THEN ELSE END col3 c)

  • 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.
    
  • Problems with Insert by using dynamic Sql

    Hello
    I use the following procedure to read a BLOB after download tab-delimited text files and insert the data in a table called TBL_TMP. The columns of the table are the following: T1, T2, T3, T4, T5, T6, T7, T8, T9. I have different text files.

    Some files could fill the table until the column T8 (v_data_array (8)) and others could fill the columns up to T9 (v_data_array (9)). So I try to change this procedure in order to take account of the text file that will fill in column T9 (v_data_array (9)) but the only thing is fails for text files that fill will alone up to T8.

    The error was: ORA-01403: no data found. I tried using NVL (v_data_array (9), 'NULL'), but it does not work. How the procedure can be modified to accept two text files containing data up to columns T8 and T9.

    Thanks in advance.
    CREATE OR REPLACE PROCEDURE pr_file_upload
      (name_in IN varchar2)
    IS
    v_blob_data       BLOB; --will hold the binary structure
    v_blob_len        NUMBER; --The length of the BLOB in bytes
    v_position        NUMBER; --Will store the current position of the pointer in the blob
    v_raw_chunk       RAW(10000); --Incremental raw chunks of the BLOB will be read in the loop
    v_char            CHAR(1); --Stores the current character of the BLOB
    c_chunk_len       NUMBER := 1; --Stores the current length of the raw chunks in bytes.
    v_line            VARCHAR2 (32767) := NULL;  --Stores the value of the current line in the loop
    v_data_array      wwv_flow_global.vc_arr2;  --apex array size of 32,000
    v_name_in         VARCHAR2 (50);
    BEGIN
    
    
    -- Read data from APEX_APPLICATION_FILES view in APEX
    SELECT blob_content INTO v_blob_data
    FROM APEX_APPLICATION_FILES WHERE filename = name_in;
    
    
    v_blob_len := dbms_lob.getlength(v_blob_data);
    v_position := 1;
    
    -- Read and convert binary to char
    WHILE ( v_position <= v_blob_len ) LOOP
     v_raw_chunk := dbms_lob.substr(v_blob_data,c_chunk_len,v_position);
     v_char :=  chr(fn_hex_to_decimal(rawtohex(v_raw_chunk)));
     v_line := v_line || v_char;
     v_position := v_position + c_chunk_len;
    -- When a whole line is retrieved
     IF v_char = CHR(10) THEN
    -- Convert tab CHR(9) to : to use wwv_flow_utilities
       v_line := REPLACE (v_line, CHR(9), ':');
    -- Convert each column separated by : into array of data
       v_data_array := wwv_flow_utilities.string_to_table (v_line);
    -- Insert data into target table
       EXECUTE IMMEDIATE 'insert into TBL_TMP (t1, t2, t3, t4, t5, t6, t7, t8, t9)
        values (:1,:2,:3,:4,:5,:6,:7,:8,:9)'
        USING
          v_data_array(1),
          v_data_array(2),
          v_data_array(3),
          v_data_array(4),
          v_data_array(5),
          v_data_array(6),
          v_data_array(7),
          v_data_array(8),
          NVL(v_data_array(9),'NULL');   -- Need help here.  This is empty when reading text files that fills up to column T8.
    
    
    -- Clear out
       v_line := NULL;
      END IF;
     END LOOP;
    END;
    /

    NVL (v_data_array (9), 'NULL') will not work. Use:

    CASE WHEN v_data_array.EXISTS(9) THEN v_data_array(9) END
    

    SY.

  • Challenges using dynamic SQL for data quality tests

    (published for the wrong forum)

    Background:

    I'm developing a data quality, mechanism, on Oracle 11 g, which uses five blocks of PL/SQL by test test script:
    < li > two to supervise the event test by inserting a record in this regard in a fact table and update after the test with the result of the counts;
    table < li > two to create an image "should be" of the tested data set and store it in a scene.
    < li > and the remaining block to perform the analysis by selecting a union of the staging table data and the data "such what" of the target table, abandoning all matching files so that only incompatibilities (errors) remain and store this information in a results table, labeled with either recording source "should be" ("should be") or target ("such what").

    I intend to do this pilot by the data, so that each block is stored as a value in an array of scripts, associated with one or more test scripts through the record key values and pulled in a SQL statement execution by a stored procedure in a package called by Informatica Oracle dynamic. In this way, a variety of data quality tests can be programmed as automated controls that work every night and trigger alerts if problems are detected.

    I have two challenges:
    < li > PL/SQL blocks that create the DataSet "should be" can be very long, and I learned through Discussion Forums OTN size maximum of 32767 K for a string of PL/SQL variable cannot be large enough to fit the entire block, and the EXECUTE IMMEDIATE statement accepts not the CLOB.
    < li > if there is no anomaly, the trick of COUNT () ON the PARTITION that I use to get the counts of subquery won't work, because the analysis block everything is an INSERT INTO < i > < /i > table (column1, Column2, etc.) SELECT (< i > < /i > comparison query) statement, to avoid that my duty to hit the table target several times. My approach to this is driven by performance problems.

    First question: can I I EXECUTE IMMEDIATE nest, so that the SQL block running offers another EXECUTE IMMEDIATE statement that calls another block of SQL? This would solve my problem first.
    Second question: what is the way most effective to get the record account of subqueries in an INSERT INTO (SELECT) statement? I feel I'm too close the code to see the obvious answer here.

    Here is a shell of the block analysis ((deuxieme question):
    DECLARE
    
    StartDate DATE;
    EndDate DATE;
    TEST_KEY NUMBER;
    
    BEGIN
    
    INSERT INTO TEST_EVENT_DETAIL 
        (TEST_EVENT_KEY,TEST_EVENT_DETAIL_KEY,COLUMN1,COLUMN2,COLUMN3,COLUMN4,
        COLUMN5)
    SELECT
        TEST_KEY as TEST_EVENT_KEY,
        TEST_EVENT_DETAIL_SEQ.NEXTVAL AS TEST_EVENT_DETAIL_KEY,
        RESULTS.TABLENAME as COLUMN1,
        RESULTS.COLUMNNAME1 as COLUMN2,
        RESULTS.COLUMNNAME2 as COLUMN3,
        RESULTS.subqry_count as COLUMN4,
        null as COLUMN5  -- there are more generic columns, this is just an example; columns not used by a particular test are filled with nulls
    FROM
    (SELECT MIN(TABLENAME) as TABLENAME,
        min(subqry_count) as subqry_count, 
        COLUMNNAME1,
        COLUMNNAME2
      FROM 
    (SELECT TABLENAME as TABLENAME,
        count(TABLENAME) over (partition by TABLENAME) subqry_count,
        COLUMNNAME1,
        COLUMNNAME2
      from
    (
    /** Source Data **/
     SELECT 'SOURCE' as TABLENAME,
        COLUMNNAME1,
        COLUMNNAME2
       FROM TEST_EVENT_STAGE A
     WHERE A.TEST_EVENT_KEY=TEST_KEY
      UNION ALL
    /** Target Data **/
      SELECT 'TARGET' as TABLENAME,
        COLUMNNAME1,
        COLUMNNAME2
      FROM TABLENAME B
      WHERE ____________
    ) TMP
    )
    GROUP BY COLUMNNAME1, COLUMNNAME2
    HAVING COUNT(*) = 1 -- this drops out all records that don't match
    ORDER BY COLUMNNAME1, COLUMNNAME2, TABLENAME ASC
    ) RESULTS;
    
    END;
    and here's some pseudocode for the stored procedure that would call the PL/SQL (first question) blocks:
    Declare
    
    TestProcessStart DATE;
    TestKey     NUMBER;
    StartDate      DATE;
    EndDate      DATE;
    BlockStatus        varchar2(200);
    BlockSQL        varchar2(32767);
    
    begin
     
    Set BlockSQL=(select SCRIPT_BLOCK from DIM_SCRIPTS where SCRIPT_KEY=(select SQL_BLOCK2 from DIM_TEST where TEST_KEY=TestKey));
    
    execute immediate 'begin ' || BlockSQL || '; end;'
       using in BlockSQL, in out BlockStatus ;
    
     if BlockStatus != 'OK' then
        dbms_output.put_line('error');
     end if;
    end;
    Any ideas/recommendations?

    PL/SQL blocks that create the data set "should be" can be very long, and I learned through the Forums of Discussion OTN 32767 K maximum size for a string of PL/SQL variable cannot be large enough to fit the entire block, and the EXECUTE IMMEDIATE statement does not accept the CLOB.

    Not in 11g more: EXECUTE IMMEDIATE statement:

    »
    dynamic_sql_stmt

    Literal string, string variable or string expression representing a SQL statement. Its type must be CHAR, VARCHAR2 or CLOB.
    «

  • insufficient privileges when using dynamic sql statements in the procedure

    Hello
    I use following script on oracle 10g. and get the error not enough privs. Please advice.

    SQL > show user
    The user is 'GRSADM '.
    SQL > create or replace procedure grsadm.test_proc as
    a varchar2 (2000);
    Start
    a: =' VIEW to CREATE or REPLACE
    TEST_VIEW
    IN SELECT
    "FLAS" one
    THE DOUBLE ';
    immediately run one;
    end;
    Created procedure.
    SQL > start
    grsadm.test_proc;
    end;
    Start
    grsadm.test_proc;
    end;
    Error on line 16
    ORA-01031: insufficient privileges
    ORA-06512: at "GRSADM. TEST_PROC', line 9
    ORA-06512: at line 2

    SQL > select * from session_privs
    where the privilege as "VIEW %.

    PRIVILEGE
    ----------------------------------------
    CREATE A VIEW
    REMOVE ANY VIEW
    CREATE A MATERIALIZED VIEW
    MODIFY A MATERIALIZED VIEW
    REMOVE ANY MATERIALIZED VIEW


    5 selected lines.

    Published by: Rous Sharma on November 24, 2011 12:00

    GRSADM has a privilege ' CREATE (all) VIEW ' live?
    And not via a role...

    SSM
    Samir,
    GRSADM is the owner of this procedure, it seems that the EXECUTE priv, that you suggested is already involved.

  • Same link several times variable using dynamic SQL

    Salvation;
    I have a query that uses the variable even several times, is there a way I could just use that variable only once and it will take several times.
    Request is;
    run immediately "SELECT count (*) x WHERE MONTH_ID =: VOMNTH_ID"
    UNION
    SELECT count (*) FROM Y WHERE MONTH_ID =: VOMNTH_ID
    Union
    SELECT count (*) FROM WHERE MONTH_ID = z: VOMNTH_ID ' help months1, month1, months1
    What I don't want only once to provide months1.
    Your help is appreciated.
    PKM
    execute immediate
      'with p as (select :vmonth_id pmon from dual)
    SELECT count(*) FROM x,p WHERE MONTH_ID = p.pmon
    UNION
    SELECT count(*) FROM Y,p WHERE MONTH_ID = p.pmon
    union
    SELECT count(*) FROM z,p WHERE MONTH_ID =p.pmon '
    using month1;
    

    HTH

    Nigel cordially

  • drop and re-create the table using dynamic sql

    The following procedure should drop the table and re-create it. Currently, I get the dbms_output of the query. If I run the query only, it works well. but through the procedure, it does not work. Please help me

    PROCEdure emp_backup is
    sql_txt varchar2(10000);
    begin
         begin
         EXECUTE IMMEDIATE 'drop table emp_backup ' ;
         exception
         when others then
         null;
    
         sql_txt:= 'CREATE TABLE emp_backup as ' ||
                     'select * from emp  '||
                     'where dep_no=10 ' ;
         dbms_output.put_line(sql_txt);
         EXECUTE IMMEDIATE sql_txt;
    Exception
    when others then
    Null;
    
    End;

    Daniel wrote:
    I'm getting following error ORA-01031: insufficient privileges

    What is the command to grant privileges to this

    GRANT CREATE TABLE TO <>
    

    Detaching Frank, however, and echoing my previous comment, let them down and to re-create the tables makes no sense. It is logical to truncate a table if you test a load. If you build a data warehouse, it makes sense to delete and re-create a partition if you rerun a load for a particular date and that you have daily partitions. Deletion and recreation of a table in a stored procedure is not a reasonable way to test a system (nor is there a reasonable way to approach change control issues that will inevitably produce when you need to change the structure of a table).

    Justin

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

  • How to get sql % number of dynamic sql code lines

    Hello

    In this procedure I'm inserting and updating using dynamic sql. Now I want to go back two more PARAMETERS, the parameter should be back the number of lines inserted and how updated by stmtas of UPDATE as well as an INSERT. I'm not able to do can help you on that?

    CREATE OR REPLACE PROCEDURE Sp_Array_Test( PV_TGT_NAME   IN  VARCHAR2,
                                               PV_SRC_NAME   IN  VARCHAR2,
                                               PV_PK_COLS    IN  VARCHAR2,
                                               PN_ERR_CD     OUT NUMBER,
                                               PN_ERR_MSG    OUT VARCHAR2)
    AS
    
    
    TYPE ARR_TAB IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;
    
    
    --UTL_FP        UTL_FILE.FILE_TYPE;
    LV_AN_
    
    
    
    BLOCK   VARCHAR2(32767);
    LN_CUR        BINARY_INTEGER := DBMS_SQL.OPEN_CURSOR;
    LN_DESC       DBMS_SQL.DESC_TAB;
    LN_COL_CNT    PLS_INTEGER := 0;
    LV_SEL_UPD_STMT   VARCHAR2(4000);
    LV_SEL_INS_STMT   VARCHAR2(4000);
    ARR_INDX      NUMBER := 1;
    LV_DATA_TYPE  VARCHAR2(8);
    LN_FIND_FLAG  NUMBER := 0;
    LN_TAB        ARR_TAB;
    LV_COLS_ARR   ARR_TAB;
    LV_ERR_MSG    VARCHAR2(500);
    
    
    
    
    --PROCEDURE FILE_WRITE ( FH_IN     IN UTL_FILE.FILE_TYPE,
    --                STRING_IN IN VARCHAR2 ) IS
    --BEGIN
    --   UTL_FILE.PUT_LINE(FH_IN,STRING_IN);
    --   LV_AN_BLOCK := LV_AN_BLOCK||STRING_IN;
    --EXCEPTION
    --   WHEN OTHERS THEN
    --      RAISE;
    --END FILE_WRITE;
    
    
    
    
    BEGIN
    
    
    --   UTL_FP := UTL_FILE.FOPEN('TEST_DIR', 'TEST.sql', 'W');
    
    
        LV_SEL_UPD_STMT := 'SELECT A.'||REPLACE(PV_PK_COLS,',','||A.')||' PK_COLS , A.* , B.ROWID FROM '||PV_SRC_NAME||' A, '||PV_TGT_NAME||' B WHERE ';
    
    
        LV_SEL_INS_STMT := 'SELECT A.* FROM '||PV_SRC_NAME||' A WHERE NOT EXISTS (SELECT ''1'' FROM '||PV_TGT_NAME||' B WHERE ';
    
    
        LN_TAB(ARR_INDX) := 'DECLARE ';
        ARR_INDX := ARR_INDX + 1;
    
    
        LN_TAB(ARR_INDX) := 'CURSOR CUR_VIEW_UPD IS '||LV_SEL_UPD_STMT ;
        ARR_INDX := ARR_INDX + 1;
    
    
    
    
        SELECT SUBSTR(COLS,DECODE(RN,1,1,INSTR(COLS,',',1,RN-1)+1),DECODE(RN,1,INSTR(COLS,',',1,RN)-1,INSTR(COLS,',',1,RN)-INSTR(COLS,',',1,RN-1)-1))
    BULK COLLECT INTO LV_COLS_ARR
          FROM ( SELECT RN, PV_PK_COLS||',' COLS
                   FROM (SELECT ROWNUM RN
                           FROM ALL_OBJECTS
                          WHERE ROWNUM <= LENGTH(PV_PK_COLS)- LENGTH(REPLACE(PV_PK_COLS,','))+1)) ;
        FOR K IN 1 .. LV_COLS_ARR.COUNT LOOP
            LV_SEL_UPD_STMT     := LV_SEL_UPD_STMT||' A.'||LV_COLS_ARR(K)||' = ';
            LN_TAB(ARR_INDX) := ' A.'||LV_COLS_ARR(K)||' = ';
            LV_SEL_UPD_STMT     := LV_SEL_UPD_STMT||' B.'||LV_COLS_ARR(K) ||CASE WHEN K = LV_COLS_ARR.COUNT THEN NULL ELSE ' AND ' END;
            LN_TAB(ARR_INDX) := LN_TAB(ARR_INDX)||' B.'||LV_COLS_ARR(K) ||CASE WHEN K = LV_COLS_ARR.COUNT THEN ' ;' ELSE ' AND ' END;
            ARR_INDX := ARR_INDX + 1;
        END LOOP;
    
    
        LN_TAB(ARR_INDX) := 'CURSOR CUR_VIEW_INS IS '||LV_SEL_INS_STMT ;
        ARR_INDX := ARR_INDX + 1;
    
    
        FOR K IN 1 .. LV_COLS_ARR.COUNT LOOP
            LV_SEL_INS_STMT     := LV_SEL_INS_STMT||' A.'||LV_COLS_ARR(K)||' = ';
            LN_TAB(ARR_INDX) := ' A.'||LV_COLS_ARR(K)||' = ';
            LV_SEL_INS_STMT     := LV_SEL_INS_STMT||' B.'||LV_COLS_ARR(K) ||CASE WHEN K = LV_COLS_ARR.COUNT THEN NULL ELSE ' AND ' END;
            LN_TAB(ARR_INDX) := LN_TAB(ARR_INDX)||' B.'||LV_COLS_ARR(K) ||CASE WHEN K = LV_COLS_ARR.COUNT THEN ' );' ELSE ' AND ' END;
            ARR_INDX := ARR_INDX + 1;
        END LOOP;
    
    
    
    
        LV_ERR_MSG := 'WHILE PARSING SELECT STATEMENT -- '||LV_SEL_UPD_STMT;
        DBMS_SQL.PARSE(LN_CUR, LV_SEL_UPD_STMT, DBMS_SQL.NATIVE);
    
    
        LV_ERR_MSG := 'WHILE DESCRIBING SELECT STATEMENT -- '||LV_SEL_UPD_STMT;
        DBMS_SQL.DESCRIBE_COLUMNS(LN_CUR, LN_COL_CNT, LN_DESC);
    
    
    
    
    
    
       FOR i IN LN_DESC.FIRST .. LN_DESC.LAST LOOP
          IF LN_DESC(i).col_type = 2 THEN
             LV_DATA_TYPE := 'NUMBER';
          ELSIF LN_DESC(i).col_type = 12 THEN
             LV_DATA_TYPE := 'DATE';
          ELSE
             LV_DATA_TYPE := 'VARCHAR2';
          END IF;
           LN_TAB(ARR_INDX) := '   T_'||LN_DESC(i).col_name||' DBMS_SQL.'||LV_DATA_TYPE||'_TABLE;';
           ARR_INDX := ARR_INDX + 1;
       END LOOP;
    
    
    
    
    
    
        LN_TAB(ARR_INDX) := 'BEGIN ';
        ARR_INDX := ARR_INDX + 1;
        LN_TAB(ARR_INDX) := '   EXECUTE IMMEDIATE ''ALTER SESSION SET NLS_DATE_FORMAT = ''''DD-MON-YYYY HH24:MI:SS'''''';';
        ARR_INDX := ARR_INDX + 1;
        LN_TAB(ARR_INDX) := '   OPEN CUR_VIEW_UPD;';
        ARR_INDX := ARR_INDX + 1;
        LN_TAB(ARR_INDX) := '   LOOP';
        ARR_INDX := ARR_INDX + 1;
        LN_TAB(ARR_INDX) := '      FETCH CUR_VIEW_UPD BULK COLLECT INTO T_'||LN_DESC(LN_DESC.FIRST).col_name||',';
        ARR_INDX := ARR_INDX + 1;
        FOR i IN LN_DESC.FIRST + 1 .. LN_DESC.LAST - 1 LOOP
          LN_TAB(ARR_INDX) := '                        T_'||LN_DESC(i).col_name||',';
          ARR_INDX := ARR_INDX + 1;
        END LOOP;
       LN_TAB(ARR_INDX) := '                        T_'||LN_DESC(LN_DESC.LAST).col_name||' LIMIT 500 ;';
       ARR_INDX := ARR_INDX + 1;
       LN_TAB(ARR_INDX) := '     FORALL I IN 1 .. '||'T_'||LN_DESC(LN_DESC.LAST).col_name||'.COUNT ';
       ARR_INDX := ARR_INDX + 1;
        LN_TAB(ARR_INDX) := '      UPDATE '||PV_TGT_NAME||' SET  ';
        ARR_INDX := ARR_INDX + 1;
        LN_FIND_FLAG := 0;
        FOR I IN LN_DESC.FIRST + 1 .. LN_DESC.LAST-1 LOOP
          FOR K IN 1 .. LV_COLS_ARR.COUNT LOOP
             LN_FIND_FLAG := 0;
             IF LN_DESC(I).COL_NAME = LV_COLS_ARR(K) THEN
                LN_FIND_FLAG := 1;
                EXIT;
             END IF;
          END LOOP;
          IF LN_FIND_FLAG = 0 THEN
            LN_TAB(ARR_INDX) := '                        '||LN_DESC(i).col_name||' = '||'T_'||LN_DESC(i).col_name||'(I)'||CASE WHEN I = LN_DESC.LAST-1 THEN ' WHERE ' ELSE ',' END;
            ARR_INDX := ARR_INDX + 1;
          END IF ;
        END LOOP;
    
    
       LN_TAB(ARR_INDX) := '                        ROWID = '||'T_'||LN_DESC(LN_DESC.LAST).col_name||'(I) ;';
       ARR_INDX := ARR_INDX + 1;
    
    
       LN_TAB(ARR_INDX) := '      COMMIT;';
       ARR_INDX := ARR_INDX + 1;
    
    
       LN_TAB(ARR_INDX) := '      EXIT WHEN CUR_VIEW_UPD%NOTFOUND;';
       ARR_INDX := ARR_INDX + 1;
    
    
       LN_TAB(ARR_INDX) := '   END LOOP;';
       ARR_INDX := ARR_INDX + 1;
    
    
       LN_TAB(ARR_INDX) := '   CLOSE CUR_VIEW_UPD;';
       ARR_INDX := ARR_INDX + 1;
    
    
       LN_TAB(ARR_INDX) := '      COMMIT;';
       ARR_INDX := ARR_INDX + 1;
    
    
    
    
        LN_TAB(ARR_INDX) := '   OPEN CUR_VIEW_INS;';
        ARR_INDX := ARR_INDX + 1;
        LN_TAB(ARR_INDX) := '   LOOP';
        ARR_INDX := ARR_INDX + 1;
        LN_TAB(ARR_INDX) := '      FETCH CUR_VIEW_INS BULK COLLECT INTO T_'||LN_DESC(LN_DESC.FIRST+1).col_name||',';
        ARR_INDX := ARR_INDX + 1;
        FOR i IN LN_DESC.FIRST + 2 .. LN_DESC.LAST - 2 LOOP
          LN_TAB(ARR_INDX) := '                        T_'||LN_DESC(i).col_name||',';
          ARR_INDX := ARR_INDX + 1;
        END LOOP;
       LN_TAB(ARR_INDX) := '                        T_'||LN_DESC(LN_DESC.LAST-1).col_name||' LIMIT 500 ;';
       ARR_INDX := ARR_INDX + 1;
    
    
       LN_TAB(ARR_INDX) := '     FORALL J IN 1 .. '||'T_'||LN_DESC(LN_DESC.FIRST + 1).col_name||'.COUNT ';
       ARR_INDX := ARR_INDX + 1;
       LN_TAB(ARR_INDX) := '     INSERT INTO '||PV_TGT_NAME||' (';
       ARR_INDX := ARR_INDX + 1;
        FOR i IN LN_DESC.FIRST + 1 .. LN_DESC.LAST - 1 LOOP
          LN_TAB(ARR_INDX) := '                        '||LN_DESC(i).col_name||CASE WHEN I = LN_DESC.LAST - 1  THEN ' )' ELSE ',' END ;
          ARR_INDX := ARR_INDX + 1;
        END LOOP;
        FOR i IN LN_DESC.FIRST + 1 .. LN_DESC.LAST - 1 LOOP
          LN_TAB(ARR_INDX) := CASE WHEN I = LN_DESC.FIRST + 1 THEN 'VALUES (' ELSE NULL END ||'                        T_'||LN_DESC(i).col_name||'(J)'||CASE WHEN I = LN_DESC.LAST - 1  THEN ' ) ;' ELSE ',' END ;
          ARR_INDX := ARR_INDX + 1;
        END LOOP;
    
    
       LN_TAB(ARR_INDX) := '      COMMIT;';
       ARR_INDX := ARR_INDX + 1;
    
    
       LN_TAB(ARR_INDX) := '      EXIT WHEN CUR_VIEW_INS%NOTFOUND;';
       ARR_INDX := ARR_INDX + 1;
    
    
       LN_TAB(ARR_INDX) := '   END LOOP;';
       ARR_INDX := ARR_INDX + 1;
    
    
       LN_TAB(ARR_INDX) := '   CLOSE CUR_VIEW_INS;';
       ARR_INDX := ARR_INDX + 1;
    
    
       LN_TAB(ARR_INDX) := '      COMMIT;';
       ARR_INDX := ARR_INDX + 1;
    
    
       LN_TAB(ARR_INDX) := 'END ;';
       ARR_INDX := ARR_INDX + 1;
    
    
    
    
       FOR J IN 1 .. LN_TAB.COUNT LOOP
    --     DBMS_OUTPUT.PUT_LINE( LN_TAB(J));
    --     FILE_WRITE(UTL_FP,LN_TAB(J));
         LV_AN_BLOCK := LV_AN_BLOCK||LN_TAB(J);
       END LOOP;
    
    
    --   UTL_FILE.FCLOSE(UTL_FP);
    
    
       EXECUTE IMMEDIATE LV_AN_BLOCK;
    
    
    PN_ERR_CD    := 0;
    PN_ERR_MSG   := 'Successful Completion';
    
    
    EXCEPTION
    WHEN OTHERS THEN
    PN_ERR_CD    := SQLCODE;
    PN_ERR_MSG   := LV_ERR_MSG||' -- '||SQLERRM ;
    END;
    /
    

    Thank you all for your answers. I agree with you all. I have manged this time by adding variable bind, then run it immediately ON aid. I don't know how it's going to be training.

    From now on my side no problem I don't thank you.

  • Dynamic SQL instead of SQLLOADER

    Hello


    I use dynamic SQL to load and transform data files.

    It works well, except that for reasons of speed I load the entire file into a temporary table before loading to its final destination along the lines of; -
    insert into ap_invoices_interface (invoice_num, invoice_amount, etc....) (select field1, field2, etc from temp_table);
    It works very fast, BUT my problems come when; my example above; a field contains a non-numeric is loaded into a numeric field.

    Is anyway, once again using dynamic SQL I can QUICKLY validate before for this kind of error, without doing it on a row by row basis?

    NB: I have a table xx_interface_mapping - which maps field1 = > invoice_num, Field2 = > invoice_amount etc. - and I put this together to make the insert statement, is it possible to combine with all_tables to know the type of data in the fields and ensure that they are valid - ALL IN the SQL DYNAMICS zippy instructions?


    Thanks for the suggestions - I is not looking for you to write the code, suggest only the concepts to use to get there...


    Robert.

    You can also the values digital alpha eliminate by this way.

    with TABLE1 as)
    Select "999,99' column1 of union double all the»
    Select ' + 999.112' of all the double union. "
    Select "12321.54"of any double union. "
    Select '-12ABC0.99' of all the double union
    Select '122' in double union
    Select '9878' across double Union
    Select "xyzd" from double
    )
    SELECT * FROM TABLE1
    where LENGTH (TRIM (TRANSLATE (column1, ' + -. 0123456789', ' '))) a null value

  • dynamic SQL - column not allowed

    Hi, I had a problem about the dynamic SQL. could someone help me? Thank you.


    TableName: = Init;
    ID: = 1;


    Statement: = "insert" | TableName. "values (' |)" ID | ', mdsys.sdo_geometry (3007, null, null,)
    MDSYS.sdo_elem_info_array (1,1003,1,
    13,1003,1,
    25,1003,1,
    37,1003,1,
    49,1003,1,
    61,1003,1,
    73,1003,1,
    85,1003,1,
    97,1003,1,
    109,1003,1,
    121,1003,1,
    133,1003,1,
    145,1003,1,
    157,1003,1,
    169,1003,1,
    181,1003,1,
    193,1003,1,
    205,1003,1,
    217,1003,1,
    229,1003,1,
    ((241,1003,1), anoCone))';

    EXECUTE IMMEDIATE statement.


    error: column not allowed

    But if I use static SQL (i.e. INSERT INTO Init...), it not there no problem at all.

    Well, I still have no idea why you are wanting to use dynamic SQL statements for this (it will only add a memory load, especially if your routine is frequently called) but I have at least understood your problem.

    The first anonymous block shows using the static SQL, the second shows how to use dynamic (and you reference a declared local variable, where your problem is).

    SQL> select count(*) from object1;
    
              COUNT(*)
    ------------------
                     0
    
    Elapsed: 00:00:00.01
    SQL> declare
         anoCone     MDSYS.SDO_ORDINATE_ARRAY;
    begin
    
    insert into OBJECT1
    values
    (
         1,
         mdsys.sdo_geometry(3007, null, null,
    mdsys.sdo_elem_info_array (1,1003,1,
    13,1003,1,
    25,1003,1,
    37,1003,1,
    49,1003,1,
    61,1003,1,
    73,1003,1,
    85,1003,1,
    97,1003,1,
    109,1003,1,
    121,1003,1,
    133,1003,1,
    145,1003,1,
    157,1003,1,
    169,1003,1,
    181,1003,1,
    193,1003,1,
    205,1003,1,
    217,1003,1,
    229,1003,1,
    241,1003,1),
    anoCone));
    
    end;
    /
    
      2    3    4    5    6    7    8    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   31   32   33   34
    PL/SQL procedure successfully completed.
    
    Elapsed: 00:00:00.00
    SQL> SQL>
    SQL> select count(*) from object1;
    
              COUNT(*)
    ------------------
                     1
    
    Elapsed: 00:00:00.01
    SQL> roll
    Rollback complete.
    SQL> select count(*) from object1;
    
              COUNT(*)
    ------------------
                     0
    
    Elapsed: 00:00:00.01
    SQL> declare
         anoCone     MDSYS.SDO_ORDINATE_ARRAY;
    begin
    
    execute immediate 'insert into ' || 'OBJECT1' || '
    values
    (
         1,
         mdsys.sdo_geometry(3007, null, null,
    mdsys.sdo_elem_info_array (1,1003,1,
    13,1003,1,
    25,1003,1,
    37,1003,1,
    49,1003,1,
    61,1003,1,
    73,1003,1,
    85,1003,1,
    97,1003,1,
    109,1003,1,
    121,1003,1,
    133,1003,1,
    145,1003,1,
    157,1003,1,
    169,1003,1,
    181,1003,1,
    193,1003,1,
    205,1003,1,
    217,1003,1,
    229,1003,1,
    241,1003,1),
    :anoCone)) ' using anoCone;
    
    end;
    /
      2    3    4    5    6    7    8    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   31   32   33   34
    PL/SQL procedure successfully completed.
    
    Elapsed: 00:00:00.01
    SQL>
    select count(*) from object1;SQL> 
    
              COUNT(*)
    ------------------
                     1
    
    Elapsed: 00:00:00.01
    SQL> 
    
  • Dynamic SQL is a valid option?

    Hello

    I have question on insertion I have a large amount of lines that I want to insert into a table. Insert rows are like;

    001 09 00 FF
    001 09 FF 11
    FF 00 11 001
    001 00 01 00

    There are four types of conditions. Only the last condition can be inserted, while the rest cannot be inserted (in other words, on four columns to all who have the value 'FF' must not be inserted).

    I wanted to use a simple constraint checking, but our DBA is not agree on this. The reason is that overall with many conditions will create a problem with the database-level locking.

    Now, I think to use dynamic SQL and the place of the condition in the WHERE clause. I think right and make any sense?

    I think I have to be aware of performance because there will be a mass insertion.

    Published by: uk113 on July 28, 2009 06:03

    In fact, I agree with kind of your DBA, but not his reasons. A check against the content of a column constraint will not cause a locking more in the database column without constraint. If you update a row in the table, Oracle will have a lock on the rows updated if they are limited or not. A newly inserted row never "locked" because it is no longer visible in the session that he introduced to the validation of this session.

    You say "I have a lot of lines that I want to insert into a table" which implies to me that you have the source data in an accessible form electronically, which means you can do single insertion as a SQL statement. As many others have suggested, I would use a predicate on each of the columns that cannot contain FF to remove these rows from the result set that you will use to make the insertion.

    Given the constraints on the table for a loading block, particulalry if you know you will have a fairly large number of rows in your data source, which will infringe the constraint actually will force you in a row by row (or bulk collect bulk collect) scenario so that you can catch constraint violations and throw these lines. Although you can still use a predicate to filter the lines that would not allow the validation.

    If you need constraints after loading mass will depend on whether or not you expect to get new data in the table, and how it will be inserted or updated. If new data come mainly from single row inserts and updates (for example from the application screen), then I would certainly limit the columns to allow not FF. If you do only loads in bulk, I would add probably not these constraints. If you are likely to have a mix of bulk and individual tips, I add the constraints, but still have a predicate in loads in bulk to filter incorrect records.

    John

  • A loop dynamic sql in the procedure

    Hi guys,.

    I'm having a procedure that will have two input start_date and end_date parameters

    I need a loop in alter procedure statement something like this using dynamic sql


    CHANGE TABLE M1

    SWAP PARTITION FOR (TO_DATE('01-JAN-2015','dd-MON-yyyy'))

    WITH TABLE T2

    INCLUDING THE INDEX;

    CHANGE TABLE M1

    BY EXCHANGE COMPETITION FOR (TO_DATE('02-JAN-2015','dd-MON-yyyy'))

    WITH TABLE T3

    INCLUDING THE INDEX;

    .

    .

    .


    For example I have dates in setting something like January 1, 2015-4 January 2015

    I need something like this, where T is a constant variable, I need to add T1, T2. T3 according to the dates of the range.

    Hello

    your procedure can not simply be rolled up, but the call session can be rolled up the output to a file.

    Try something like this

    col act_date noprint new_value act_date
    
    SET TERMOUT  OFF
    
    select to_char(sysdate, 'yyyy_mm_dd_hh24miss') act_date
      from dual;
    
    SET TERMOUT      ON
    set serveroutput on
    set feedback     off
    set linesize     3000
    
    col statement for a200 heading "-- alter statements"
    
    spool d:\temp\&act_date._&_CONNECT_IDENTIFIER._alter_partition.sql
    
    -- exec your_procedure
    
    -- or simple plain sql
    
    with data (start_date, end_date) as (
      select to_date('01/01/2016', 'dd/mm/yyyy'),
            to_date('05/01/2016', 'dd/mm/yyyy')
        from dual
        )
    select --level, to_char(start_date + (level - 1), 'dd-MON-yyyy' ) cur_date
                     'ALTER TABLE M1 EXCHANGE PARTITION FOR (TO_DATE(''' || to_char(start_date + (level - 1), 'dd-MON-yyyy' ) || ''',''dd-MON-yyyy'')) WITH TABLE T2 INCLUDING INDEXES;'
      || chr(10) ||  'ALTER TABLE M1 EXCHANGE PARTITION FOR (TO_DATE(''' || to_char(start_date + (level - 1), 'dd-MON-yyyy' ) || ''',''dd-MON-yyyy'')) WITH TABLE T3 INCLUDING INDEXES;'  as statement
      from data
    connect by level <= end_date - start_date + 1;
    
    spool off
    
    set feedback    on
    
    prompt @d:\temp\mk_alter.sql
    

    concerning
    Kay

Maybe you are looking for

  • Stopping ANNOYING ads

    How can I stop them altogether? If you can't do it I'll just uninstall Skype.

  • Satellite L300-1BW - BSOD and then the password at startup appeared

    Hello I'm new hear that ive just got a laptop Toshiba L300 - 1bw Windows vista, intel celeron. I changed the laptop on it gives the initial toshiba screen then goes to a blue screen and request a password. I tried f8 when turning on pc ive tried f12

  • Satellite A200 - its possible to change my video card?

    Hey,. I was wondering if its possible to change my video for a better card. I currently have the nVidia GeForce Go 7300 and its an integrated video card.But I don't know if this means that it is impossible to change it or maybe its possible to add an

  • Can power supply Question - I use the 230W power supply with a W540?

    I have a W540, which currently uses a power 170W (8.5 a 20V) I got also a docking station for a P50 that has a power of 230W showing 20V 11. 5a. The connectors are similar, but I'm hesitant to try the 230W power supply in the W540. It is allowed to u

  • Attempt to scam "Event Viewer".

    How can I report an attempted scam called "Event Viewer". I asked for a number to call after that I checked with a friend. He gave me a number in Ohio - 614-388-8812. I live near Toronto in the Canada.