Monday, February 27, 2012

Working with Trigger in Oracle

I want to implement autoincrement feature to my employee table.Built in facility is not available but we can write our own trigger concept to do so.

1. Create table in Oracle
------------

 create table Employee1
  (
    empid number primary key,
    empname varchar2(10),
    empsal number(10,2)
   );

2.Create a Sequence which will generate unique empid each time

SQL> CREATE SEQUENCE   EMPID_SEQ  MINVALUE 101 MAXVALUE 1000 INCREMENT BY 1 START WITH 101 NOCACHE   NOCYCLE  NOORDER;

3.Write a Trigger,which will insert the value from empid_seq to empid column of Employee1 table

SQL>
CREATE OR REPLACE TRIGGER EMPID_TRIG
before insert on EMPLOYEE1
for each row
begin
select EMPID_SEQ.nextval into :new.EMPID from dual;
end;
/
ALTER TRIGGER EMPID_TRIG ENABLE;

4.Insert record into table without EmpId.Notice that EmpId is autofilled by sequence value.
SQL>  insert into employee1(empname,empsal) values('suraj',1000);
SQL>   insert into employee1(empname,empsal) values('raj',200);




5>View Record to see the autoIncrement working
SQL> select * from employee1;

     EMPID EMPNAME        EMPSAL
---------- ---------- ----------
       101 suraj            1000
       102 raj               200


No comments:

Post a Comment