HiveBrain v1.2.0
Get Started
← Back to all entries
patternMajor

Is commit necessary after DML operation in Function/Procedure?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
aftercommitnecessaryfunctionoperationproceduredml

Problem

I wonder to know if it is necessary to write commit after insert/delete/update in function/procedure?

Example:

create or replace function test_fun
return number is
begin
   delete from a;
   return 0;
end;


or procedure

create or replace procedure aud_clear_pro
as
begin
   delete from a;
end;


does it need commit after delete?

Cannot understand the following situation:

-
If I call the function/procedure from SQL window then it requires commit

but

-
If I schedule function/procedure using dbms_scheduler and run the job, delete statement is automatically committed.

WHY?

Solution

In general, procedures should not commit. Those sorts of transaction control decisions should be left to higher-level code that knows when a logical transaction is actually complete. If you commit inside of a stored procedure, you are limiting its reusability because a caller that wants the changes the procedure makes to be part of a larger transaction cannot simply call the procedure directly.

If you call a procedure interactively, you will have to explicitly commit or rollback the transaction because Oracle has no idea if you intend the procedure call to be a logical transaction or if you intend to compose a larger transaction involving multiple procedure calls. If you use dbms_scheduler, dbms_scheduler assumes that a job is a logical transaction and commits at the end of the job assuming it was successful (dbms_job does the same thing).

Functions should not manipulate data in the first place. A function that manipulates data cannot be called from a SQL statement (barring the corner case where the function itself is declared to use an autonomous transaction which is almost never appropriate). The whole point of having both functions and procedures is that functions can be embedded in SQL statements and can be more freely granted to users because they do not change any data.

Context

StackExchange Database Administrators Q#17533, answer score: 24

Revisions (0)

No revisions yet.