Ask the Expert

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?

    Requires Free Membership to View

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

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

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: