Trigger to generate autoincrement column in Oracle Database

      In this article, I will introduce how to use oracle trigger to generate autoincrement column in oracle database. I will use an example here to illustrate.

1. Create a table in oracle database.

 

View Code
CREATE   TABLE  USER_INFO
(
   
User_ID   integer   primary   key , -- Primary key
    User_Name   varchar2 ( 20 ),
   sex 
varchar2 ( 2 )
);
select   *   from  user_info;

 

 2. Create a autoincrement sequence.

 

View Code
CREATE  SEQUENCE User_Info_SEQ
minvalue 
1
maxvalue 
9999999999999999999
increment 
by   1
start 
with   1 ;

3. Create the Trigger.

 

View Code
CREATE   OR   REPLACE   TRIGGER  TRI_User_Info_I
BEFORE 
INSERT   ON  User_Info  /* *Toggle Condition.* */
for  each row  /* *Each line test for the trigger.* */
begin
   
select  User_Info_Seq.Nextval  into  :NEW. User_ID   from  dual;
end ;

4. Test the Trigger.

 

View Code
insert   into  user_info( user_name ,sex)  values ( ' David.Tian ' , ' M ' );

insert   into  user_info( user_name ,sex)  values ( ' Lucy ' , ' F ' );

commit ;

select   *   from  user_info;

Conclusion: Now I have finsih the functionality. If you have any issues or a better way to realize this, please send me email. My email is [email protected]

                 You can also download this script:Use_Trigger_to_Generate_Autoincrement_column

 

你可能感兴趣的:(database)