Thursday, June 09, 2005

Oracle Trigger Example / autoincrement


I found it here, http://www.cis.upenn.edu/~cis550/trigger.sql (see inline below)

Here's a way to create a table in Oracle with a field set to auto increment. It's pretty simple but make sure you see the / after the end statement of the create trigger statement

/* trigger example */
/* written by Marcus Haebler (haebler@gradient.cis.upenn.edu) */
/* before we create something we drop it */
drop sequence sqtest;
/* create a sequence */
create sequence sqtest increment by 1 start with 1;
/* before we create something we drop it */
/* drop trigger ... is not really necessary, triggers are droped with tables */
drop trigger test_trigger_trigger;
drop table test_trigger;
/* create our little test table */
create table test_trigger (
id integer primary key,
name varchar2(16)
);
/* create our trigger be aware of the / after the end;!!! It is needed */
create trigger test_trigger_trigger
before insert on test_trigger
for each row
begin
/* insert primary key */
select sqtest.nextval into :new.id from dual;
/* make sure all names are upper case */
:new.name := UPPER(:new.name);
end;
/
/* some testing */
insert into test_trigger (name) values ('a');
insert into test_trigger (name) values ('b');
select * from test_trigger;

0 Comments:

Post a Comment

<< Home