Q

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


This was first published in June 2003

Dig deeper on Oracle database design and architecture

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close