CREATE TABLE departments ( ID NUMBER(10) NOT NULL, DESCRIPTION VARCHAR2(50) NOT NULL);
ALTER TABLE departments ADD ( CONSTRAINT dept_pk PRIMARY KEY (ID));
CREATE SEQUENCE dept_seq; /Finally we can test it using the automatic and manual population methods:
SQL> INSERT INTO departments (description)
2 VALUES ('Development');
1 row created.
SQL> SELECT * FROM departments;
ID DESCRIPTION
---------- --------------------------------------------------
1 Development
1 row selected.
SQL> INSERT INTO departments (id, description)
2 VALUES (dept_seq.NEXTVAL, 'Accounting');
1 row created.
SQL> SELECT * FROM departments;
ID DESCRIPTION
---------- --------------------------------------------------
1 Development
2 Accounting
2 rows selected.
The trigger can be modified to give slightly different results. If the insert trigger needs to perform more functionality than this one task you may wish to do something like:
CREATE OR REPLACE TRIGGER dept_bir
BEFORE INSERT ON departments
FOR EACH ROW
BEGIN
SELECT NVL(:new.id, dept_seq.NEXTVAL)
INTO :new.id
FROM dual;
-- Do more processing here.
END;
/To overwrite any values passed in you should do the following:
CREATE OR REPLACE TRIGGER dept_bir
BEFORE INSERT ON departments
FOR EACH ROW
BEGIN
SELECT dept_seq.NEXTVAL
INTO :new.id
FROM dual;
END;
/To error if a value is passed in you should do the following:
CREATE OR REPLACE TRIGGER dept_bir
BEFORE INSERT ON departments
FOR EACH ROW
BEGIN
IF :new.id IS NOT NULL THEN
RAISE_APPLICATION_ERROR(-20000, 'ID cannot be specified');
ELSE
SELECT dept_seq.NEXTVAL
INTO :new.id
FROM dual;
END IF;
END;
/Hope this helps. Regards Tim...
--------------------------------------------------------------------------------
Below have some examples for reference.
--------------------------------------------------------------------------------
Example Number 1 ...
create sequence product_seq start with 1 increment 1
/
create or replace trigger product_insert before insert for each row begin
select productseq.nextval
into :new.product_id
from dual;
end;
/
Example Number 2 ... How to create an autoincrement field in a table with a sequence ...
SQLWKS> create table bob(a number , b varchar2(21));
Statement processed.
First create a sequence
SQLWKS> create sequence x ;
Statement processed.
Then create the trigger.
create trigger y before insert on bob
for each row
when (new.a is null)
begin
select x.nextval into :new.a from dual;
end;
/
Example Number 3 ... First create a sequence:
create sequence emp_no_seq;
By default it increments by 1 starting at 0.
Use its values when inserting data into the table:
insert into t_emp values (emp_no_seq.nexval, 'Joe Black');
没有评论:
发表评论