Often times, a default/unique value might be needed to be inserted into a column of a table which can then act as a primary or unique identifier.
The usual methodology will be to do that using a row level trigger which fires on INSERT and updates the column value with the sequence value.
The usual methodology will be to do that using a row level trigger which fires on INSERT and updates the column value with the sequence value.
SQL> create trigger tab1 2 before insert on tab1 3 for each row 4 begin 5 if (:new.x is null) 6 then 7 :new.x := s.nextval; 8 end if; 9 end; 10 / Trigger created.
This can be replaced by the below method from Oracle Database 12c.
SQL> create sequence s;
Sequence created.
SQL> create table tab1
2 ( x int
3 default s.nextval
4 primary key,
5 y varchar2(30)
6 );
Table created.
SQL> insert into tab1 (x,y)
2 values ( default, 'hello' );
1 row created.
SQL> insert into tab1 (y)
2 values ( 'world' );
1 row created.
SQL> select * from tab1;
X Y
———————— ————————
1 hello
2 world
No comments:
Post a Comment