Sunday 4 January 2015

How to use COMMIT in Oracle stored procedure



EXAMPLE  ( COMMIT Statement in stored procedure)
# Step 1 : Create a table & Insert rows by Stored Procedure
SQL> CREATE TABLE Stu_Info
            (
                 stuid number,
                 name varchar2(10),
                 city varchar2(10),
                 amount number
            );
#Step2 : Create Procedure p_insertStuInfo to insert record into table.
SQL> CREATE OR REPLACE PROCEDURE p_InsertStuInfo
          p_stuid IN number,
             p_name  IN VARCHAR2,
             p_city  IN VARCHAR2,
             p_amount IN NUMBER)
           IS
           BEGIN
              INSERT INTO Stu_info
                 values(p_stuid,p_name,p_city,p_amount);
              COMMIT;
           END;
           /

Step 3 : Execute Procedure multiple times with different values.

SQL> EXEC p_insertStuInfo(1000,'RAM','NEW DELHI',1000);
SQL> EXEC p_insertStuInfo(1001,'SACHIN','MUMBAI',2000);
SQL> EXEC p_insertStuInfo(1002,'SMITH','NEW YORK',3000);
SQL> EXEC p_insertStuInfo(1003,'CHENG','BEIJING',4000);


Setp 4 : Check table records.
SQL> SELECT * from Stu_Info;

STUID
NAME
CITY
AMOUNT
1000
RAM
NEW DELHI
1000
1001
SACHIN
MUMBAI
2000
1002
SMITH
NEW YORK
3000
1003
CHENG
BEIJING
4000

Setp 5 : Execute ROLLBACK & recheck table's data.
SQL> ROLLBACK;
SQL> SELECT * from Stu_Info;
STUID
NAME
CITY
AMOUNT
1000
RAM
NEW DELHI
1000
1001
SACHIN
MUMBAI
2000
1002
SMITH
NEW YORK
3000
1003
CHENG
BEIJING
4000

ROLLBACK doesn't affect the table's data because whenever we execute procedure it will call COMMIT and it will save subsequent data permanently. if you are using DML statements like INSERT,UPDATE or DELETE in procedure then must use COMMIT statements inside the procedure.

No comments:

Post a Comment