Issue using collect slider + dynamic SQL + loose + FORALL

Hello

I have a dynamic query I need to use a cursor to fetch recording this inturn need to insert in an intermediate table.

The issue I'm facing is that I don't know how to declare the variable to retrieve the records in. Since I use a dynamic cursor how I to declare?

My code looks something like this-
----------------------------------------------------------------------------------
TYPE c_details_tbl_type IS REF CURSOR;
c_details c_details_tbl_type;

TYPE c_det_tbl_type IS TABLE OF c_details % ROWTYPE INDEX BY PLS_INTEGER;
c_det_tbl c_det_tbl_type; -- ???
BEGIN

v_string1: = "SELECT...". »
v_string2: = 'UNION ALL SELECT '.... »
v_string3: = 'AND... '. »

v_string: = v_string1 | v_string2 | v_string3;

C_details OPEN FOR v_string;
LOOP
Fetch the c_details COLLECT in BULK
IN c_det_tbl LIMIT 1000;
IF (c_det_tbl. COUNT > 0) THEN
REMOVE FROM STG;
FORALL i IN 1.c_det_tbl. COUNTY
INSERT INTO STG
VALUES (c_det_tbl (i));
END IF;
OUTPUT WHEN c_details % NOTFOUND;
END LOOP;
NARROW C_details;
END
-------------------------------------------------

Thank you

Why most collect? Everything is slow down the process of reading (SELECT) and write (INSERT) processes.

Selected data (as a collection) needs to be pushed in the memory of the PGA of the PL/SQL engine. And then the same data must be pushed back again by the PL/SQL engine to the database to be inserted. Why?

It is much faster, needs much less resources, with fewer moving parts, simply load the SQL engine to do both these steps using a single INSERT... SELECT statement. And it can support parallel DML too for scalability when data volumes get big.

It is also quite easy to do a single SQL statement we would like this dynamic and even bind variable.

Simplicity is the ultimate form of elegance. Pushing data unnecessarily around, it's not simple and therefore not a very elegant way to solve the problem.

Tags: Database

Similar Questions

  • 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

  • Using of the dynamic SQL and the cursor in a procedure

    Here is the procedure:
    create or replace
    Procedure type_paiement_total
    is
    
        cursor xbtable is select table_name from user_tables where table_name like 'XB%';
        n_table user_tables.table_name%type;
        req     varchar2(256);
        journal varchar2(2);
        mois varchar2(2);
        an varchar2(2);
      begin
        for n_table in xbtable
        loop
          execute immediate 'insert into xx_jk_xb (
          clie_code,journal, periode,origine, xb_ecri,xb_libe  ,dos_code,xb_debi,xb_cred,xb_term
    )
    select c.code,  
    substr(:1,3,2),
    substr(:1,7,2)||substr(:1,5,2)||,
    :1,  
    xb.ecri,  
    xb.libe,  
    d.code,
    xb.debi,
    xb.cred,
    xb.terme
    from                      
    '||n_table.table_name ||' xb,
    dossier d,                      
    client c                    
    where xb.cmpt=''4111''                    
    and xb.doss  =d.code                    
    and c.code   =d.clie
    and c.role=''1''' using n_table.table_name;
          execute immediate 'insert into xx_jk_logxb (recnum,xb_ref,trsf) values (seq_logmreg.nextval,:1,''OK'')' using n_table.table_name;
          commit;
          fetch xbtable into n_table;
        end loop;
      end;
    What he does (or what I intend to do)
    take the datas of a whole bunch of pictures and put them in the "XX_JK_XB" table and make a log of the tables covered in xx_jk_logxb give just the source table and the status (OK).
    Now when I run the procedure I get a "missing expression" th ' immediate «insert into xx_jk...»» »

    I just can't tell what is the problem here.

    clues?

    Seems to me that you are wrong assuming that the binding can be done by name and no position when you use immediate enforcement.

    Example:

    SQL> create table foo_tab( c1 varchar2(10), n1 number );
    
    Table created.
    
    SQL>
    SQL> begin
      2          for i in 1..10
      3          loop
      4                  execute immediate 'insert into foo_tab values( to_char(:1), :1 )' using i;
      5          end loop;
      6          commit;
      7  end;
      8  /
    begin
    *
    ERROR at line 1:
    ORA-01008: not all variables bound
    ORA-06512: at line 4
    
    SQL>
    SQL>
    SQL> begin
      2          for i in 1..10
      3          loop
      4                  execute immediate 'insert into foo_tab values( to_char(:1), :1 )' using i,i;
      5          end loop;
      6          commit;
      7  end;
      8  /
    
    PL/SQL procedure successfully completed.
    
    SQL>
    

    As you can see, 1 PL/SQL block attempts to re - use bind variable: 1 new - and only link once.

    Fact does not work like that - you must link it again. Binding is done by bind - 1 position = 1 to the help of var, 2nd = 2nd bind using var, etc.. Name of the connection variable used is irrelevant and not unique.

  • 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

  • In Oracle 10 g error when using COLLECT

    I get the error when you use collect in 10g

    SQL > ed
    A written file afiedt.buf

    1. SELECT deptno
    2, COLLECT (ename) AS PGE
    3 FROM emp
    GROUP 4 BY
    5 * deptno
    SQL > /.
    COLLECT (ename) AS PGE
    *
    ERROR on line 2:
    ORA-00932: inconsistent data types: expected NUMBER obtained -

    Please give me the solution.

    you use the old version of SQL * more. If you use the later version, it will give you correct the result.

    Published by: ūnōrum on March 14, 2010 04:25

  • GETTING AN ERROR - slider 'P_REFCUR' cannot be used in the OPEN dynamic SQL stat

    DECLARE
    create or replace procedure partial_single (p_fileid in NUMBER, p_filename IN VARCHAR2 (2000), p_temptablename IN VARCHAR2 (2000), p_temppartialtablename IN VARCHAR2 (2000), p_retval ON the NUMBER)
    --)

    p_fileid NUMBER;
    p_filename VARCHAR2 (2000);
    p_temptablename VARCHAR2 (2000);
    p_temppartialtablename VARCHAR2 (2000);
    p_retval NUMBER;
    p_refcur types_pkg.return_cur;
    v_strquery varchar2 (4000);

    BEGIN

    p_fileid: = 5080;
    p_filename: = "TAGSUR1HM2011013111160838654.000019265";
    -p_temptablename: = "TEMP_RECORDS_MED_0004";
    p_temptablename: = 'TEMP_RECORDS_MED_DATE ';
    p_temppartialtablename: = 'TEMP_MED_PARTIAL_RECORDS_0002 ';
    p_retval: = 0;


    v_strquery: = 'SELECT imsi, connectedcallingnumber, callstart MIN (calleventstarttimestamp), SUM (calleventduration), MAX (sequence_number) sequencenumber, msisdn, max (callreleasetime) callreleasetime period';
    v_strquery: = v_strquery | ' A ' | p_temppartialtablename | ' GROUP BY connectedcallingnumber, imsi, msisdn';

    OPEN p_refcur - GETTING AN ERROR - slider 'P_REFCUR' cannot be used in a dynamic OPEN SQL statement
    FOR v_strquery;

    FOR CC IN (SELECT imsi,
    connectedcallingnumber,
    Callstart MIN (calleventstarttimestamp),
    Duration of the SUM (calleventduration),
    SequenceNumber MAX (sequence_number),
    MSISDN,
    Max (callreleasetime) callreleasetime
    OF TEMP_MED_PARTIAL_RECORDS_0002
    GROUP BY connectedcallingnumber, imsi, msisdn)

    LOOP

    UPDATE TEMP_RECORDS_MED_DATE
    SET calleventstarttimestamp = cc.callstart,
    calleventduration = calleventduration + cc.duration
    WHERE connectedcallingnumber = cc.connectedcallingnumber
    AND imsi = cc.imsi
    AND sequencenumber = cc.sequencenumber + 1
    AND msisdn = cc.msisdn
    AND calleventstarttimestamp = cc.callreleasetime;


    IF SQL % ROWCOUNT > 0
    THEN
    UPDATE TEMP_MED_PARTIAL_RECORDS_0002
    SET isprocessed = 1
    WHERE connectedcallingnumber = cc.connectedcallingnumber
    AND imsi = cc.imsi
    AND msisdn = cc.msisdn;
    - AND callreleasetime = cc.callreleasetime;

    ON THE OTHER

    UPDATE TEMP_MED_PARTIAL_RECORDS_0002
    SET calleventduration = calleventduration + cc.duration
    IMSI WHERE = cc.imsi
    AND msisdn = cc.msisdn
    AND callreleasetime = cc.callreleasetime
    AND calleventduration! = cc.duration;


    END IF;

    END LOOP;


    REMOVE FROM TEMP_MED_PARTIAL_RECORDS_0002
    WHERE isprocessed = 1;


    p_retval: = 0;

    -VALIDATION;
    / * EXCEPTION
    WHILE OTHERS
    THEN
    -RESTORATION;
    p_retval: = 1;
    p3_errorlog ("partial" p_fileid, SQLERRM, |) ':' || p_filename);
    COMMIT;
    */
    END;

    Is - what your refcursor has a return type? In this case you can not open it with dynamic SQL. Change the Refcursor as a weakly typed cursor and give it a try.

  • Using the slider for and BULK COLLECT INTO

    Hi all
    in this case we prefer to use the cursor AND the cursor with the LOOSE COLLECTION? The following contains two block this same query where used FOR the slider, the other is using COLLECT LOOSE. The task that is running better given in the existing? How do we measure performance between these two?

    I use the example of HR schema:
    declare
    l_start number;
    BEGIN
    l_start:= DBMS_UTILITY.get_time;
    dbms_lock.sleep(1);
    FOR employee IN (SELECT e.last_name, j.job_title FROM employees e,jobs j 
    where e.job_id=j.job_id and  e.job_id LIKE '%CLERK%' AND e.manager_id > 120 ORDER BY e.last_name)
    LOOP
      DBMS_OUTPUT.PUT_LINE ('Name = ' || employee.last_name || ', Job = ' || employee.job_title);
    END LOOP;
    DBMS_OUTPUT.put_line('total time: ' || to_char(DBMS_UTILITY.get_time - l_start) || ' hsecs');
    END;
    /
     
    declare
    l_start number;
    type rec_type is table of varchar2(20);
    name_rec rec_type;
    job_rec rec_type;
    begin
    l_start:= DBMS_UTILITY.get_time;
    dbms_lock.sleep(1);
    SELECT e.last_name, j.job_title bulk collect into name_rec,job_rec FROM employees e,jobs j 
    where e.job_id=j.job_id and  e.job_id LIKE '%CLERK%' AND e.manager_id > 120 ORDER BY e.last_name;
    for j in name_rec.first..name_rec.last loop
      DBMS_OUTPUT.PUT_LINE ('Name = ' || name_rec(j) || ', Job = ' || job_rec(j));
    END LOOP;
    DBMS_OUTPUT.put_line('total time: ' || to_char(DBMS_UTILITY.get_time - l_start) || ' hsecs');
    end;
    /
    In this code, I put a timestamp in each block, but they are useless, since they both launched virtually instantaneous...

    Best regards
    Val

    (1) bulk fired fresh primary use is to reduce the change of context between sql and pl sql engine.
    (2), you should always use LIMIT when it comes with bulk collect, this does not increase the load on the PGA.
    (3) and the ideal number of BOUNDARY lines is 100.

    Also if you really want to compare performance improvements between the two different approaches to sql pl try to use the package of runstats tom Kyte

    http://asktom.Oracle.com/pls/Apex/asktom.download_file?p_file=6551378329289980701

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

  • Error when using native dynamic SQL

    Please can someone help me understand what's wrong with my code.

    Code:

    create or replace procedure p1 (name varchar2)

    as

    Start

    run immediately "select * from ' |" name;

    end;

    /

    Goal: Just to test the native dynamic SQL code using a placeholder.

    COmpliation:

    SQL > create or replace procedure p1 (name varchar2)

    2 as

    3

    4 start

    5 run immediately "select * from ' |" name;

    6 end;

    7.

    Created procedure.

    Error:

    SQL > exec p1 ('employees');

    BEGIN p1 ('employees'); END;

    *

    ERROR on line 1:

    ORA-00923: THE KEYWORD not found where expected

    ORA-06512: at "HR. "P1", line 5

    ORA-06512: at line 1

    SQL >

    You need a space after the clause 'from', like this:

    run immediately "select * from ' |" name;

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

  • The generation dynamic SQL when records using custom

    Hi all

    We have a few custom folders (we did not create the views) where we joined the table of facts with several dimensions of code so that users don't need to go through several folders. Currently every time a user selects a field in the record, it will automatically joins all the dims in accordance with the definition of record. Is it possible, when the user select only the fact of the table fields in the folder then the sql access only the table of facts (as in dynamic sql) leaving aside the joints.

    I'm not positive all able to do so. But even post the question to check if there is a solution found by any one.

    Here's the hypothetical scenario:

    SQL for my custom folder:

    Select
    EMP.emp_id,
    EMP.emp_name,
    job_id EMP.,.
    jobs. job_desc,
    EMP.location_id,
    Location.location_desc,
    EMP. Salary
    of the emp, jobs, location
    where emp.job_id = jobs.job_id
    and emp.location_id = location.location_id;

    In the example above, when the user select only the emp_id and emp_name, discoverer only accesses the emp table, leaving aside joins jobs and location tables?

    Appreciate your answers.

    Hello

    There are 3 approaches you can take, which is best for you depends on your database and the version of discoverer and how much change you want to make:

    1. optimization of data - if you use database 11 g and the query sent to the database does not refer to an attachment internal table in the first select statement in the query, for example, the query

    Select
    EMP.emp_id,
    EMP.emp_name,
    job_id EMP.,.
    jobs. job_desc,
    EMP.location_id,
    EMP. Salary
    of the emp, jobs, location
    where emp.job_id = jobs.job_id
    and emp.location_id = location.location_id;

    does not reference the table of localization, so as long as location_id is the primary key for location and emp.location_id has a validated and enabled foreign key constraint then the database query plan will not otherwise the table of localization.

    2 synthesis discoverer files - you can manually set the summary files in admin discoverer that contain queries custom with less joins of tables. Thus, for example, you could put

    Select
    EMP.emp_id,
    EMP.emp_name,
    job_id EMP.,.
    jobs. job_desc,
    EMP.location_id,
    EMP. Salary
    of the emp, jobs
    where emp.job_id = jobs.job_id;

    in a personalized summary folder and discoverer would redirect the request to the summary file if the location has not been used. You can also do a similar thing to the database level using the views and materialized views.

    3. complex records discoverer - you can change your custom folder in a folder complex bringing together two or more straightforward cases. If the columns mapped to a single file are not reference, then all joins and discoverer preferences are set correctly the generated query does not reference the table in the simple folder.

    Rod West

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

  • How to execute dynamically generated using GR 11, 2 SQL statements?

    Hello

    I would like to know if it is possible to do what the following statement which is intended :
    select * from (select replace('select empno from emp',
                                 '',
                                 '') from dual);
    in other words, is it possible to dynamically generate and execute a select statement in a from clause?

    Thank you for your help,

    John

    Published by: 440bx 16 July 2010 15:57 modified 'create' to 'generate' to the subject

    Like many I know no. in SQL. Results of your query in the FROM clause will not be transformed as another query, but just a litral value and your outer query returns this value as "select empno from emp".

    But you can use dynamic sql statements in PL/SQL using EXECUTE IMMEDIATE or DBMS_SQL.

    Something like that.

    DECLARE
     dynamic_from_clause VARCHAR2(4000) := 'select empno from emp';
     vReturnVal NUMBER;
    BEGIN
      EXECUTE IMMEDIATE 'SELECT * FROM ('||dynamic_from_clause||')' into vReturnVal ;
    END;
    /
    

    Just write memory have not tested it.

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

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

Maybe you are looking for