Telling EXECUTE IMMEDIATE to commit

I have a question about EXECUTE IMMEDIATE. It does not need an explicit commit to commit DML statements. Is it possible to force it not to commit until explicitly told to do so?

The EXECUTE IMMEDIATE command does not perform an implicit commit after every iteration. To verify this, I'll show a simple test case. First, I'll create a small table:

ORA9I SQL> create table test (id number);

Table created.
Then, I'll run through a loop to insert into this table some values. After the loop is complete, I'll rollback all EXECUTE IMMEDIATE INSERT statements:
ORA9I SQL> DECLARE
  2     counter NUMBER;
  3  BEGIN
  4     FOR counter IN 1..5 LOOP
  5        EXECUTE IMMEDIATE 'INSERT INTO test VALUES
('||counter||')';
  6     END LOOP;
  7  ROLLBACK;
  8  END;
  9  /

PL/SQL procedure successfully completed.

ORA9I SQL> select * from test;

no rows selected
As you can see, my one ROLLBACK statement rolled back all five INSERT statements. This means that there was no implicit commit done with the EXECUTE IMMEDIATE command. There is an implicit commit performed with DDL statements, not DML statements. Many times, the EXECUTE IMMEDIATE is used for dynamically executing DDL statements, so this is where your confusion may have come in. And you do not need EXECUTE IMMEDIATE for most dynamic DML statements. I can simply write the above PL/SQL block as follows:
ORA9I SQL> DECLARE
  2     counter NUMBER;
  3  BEGIN
  4     FOR counter IN 1..5 LOOP
  5        INSERT INTO test VALUES(counter);
  6     END LOOP;
  7     COMMIT;
  8  END;
  9  /

PL/SQL procedure successfully completed.

ORA9I SQL> select * from test;

        ID
----------
         1
         2
         3
         4
         5
However, you will need EXECUTE IMMEDIATE if you do something like dynamically change the table name in the INSERT statement.

For More Information


Dig Deeper on Oracle database administration

Data Management
Business Analytics
SearchSAP
TheServerSide.com
Data Center
Content Management
HRSoftware
Close