Oracle自动编号触发器

时间:2016-10-26 14:20:39

标签: sql oracle oracle11g

我在Oracle(Pre 12c)中为表创建了一些SQL,当我尝试在学生表中插入值时,我的触发器似乎无法正常工作我必须为当我希望能够放置任何内容并使用数字传播时,主键。

触发

create or replace TRIGGER student_bir 
BEFORE INSERT ON student
FOR EACH ROW

WHEN (new.record_number IS NULL)
BEGIN
  SELECT student_seq.NEXTVAL
  INTO   :new.record_number 
  FROM   dual;
END;

序列

CREATE SEQUENCE  "SEQUENCE" MINVALUE 100 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 100 CACHE 20 NOORDER  NOCYCLE  NOPARTITION ;

学生表

CREATE TABLE student
(
record_number       NUMBER (8)
              CONSTRAINT  student_ref_number_pk PRIMARY KEY,

full_name         VARCHAR2(30)
              CONSTRAINT  student_full_name_nn  NOT NULL,

programme       VARCHAR2(30)
    CONSTRAINT student_programme_fk
    REFERENCES programme (programme_name),

date_of_birth DATE,

term_address    VARCHAR2(255)
              CONSTRAINT student_term_address_nn  NOT NULL,

term_postcode VARCHAR2(8)
              CONSTRAINT student_term_postcode_nn NOT NULL,

home_address    VARCHAR2(255),

home_postcode VARCHAR2(7),

mobile_number NUMBER (11)
              CONSTRAINT student_mobile_number_nn NOT NULL,

home_number     NUMBER(11),

email_address   VARCHAR(255)
              CONSTRAINT student_email_address_nn NOT NULL,


username        VARCHAR2(20)
              CONSTRAINT student_username_nn  NOT NULL
)

插入值

INSERT INTO STUDENT VALUES ('Tom', 'Networking', '', '123 lead street', 'PL48BZ', '345 HOME ROAD', 'DY15HGL', '07923584331', '01562748594', 'tom@gmail.com', 'tom22');

错误消息

Error starting at line : 1 in command -
INSERT INTO STUDENT VALUES ('Tom', 'Networking', '', '123 lead street', 'PL48BZ', '345 HOME ROAD', 'DY104TJ', '07923584339', '01562748597', 'tom.mead07@hotmail.co.uk', 'tom225666')
Error at Command Line : 1 Column : 13
Error report -
SQL Error: ORA-00947: not enough values
00947. 00000 -  "not enough values"
*Cause:    
*Action:

2 个答案:

答案 0 :(得分:1)

@Mat是对的。您的错误消息是因为insert语句期望在VALUES子句中指定每个列。

insert into student(full_name, programme, ...) values ('billy', 'Networking',...)

...并且触发器填充record_number。

答案 1 :(得分:0)

如果您指定了一个列并检查了值,则会发现忘记了record_number。从值中删除它或添加null

INSERT INTO STUDENT(
record_number
full_name,
programme,
date_of_birth,
term_address,
term_postcode,
home_address,
home_postcode,
mobile_number,
home_number ,
email_address,
username) VALUES (
<The values should be there> -- record_number
'Tom',                   -- full_name,
'Networking',            -- programme,
'',                      -- date_of_birth,
'123 lead street',       -- term_address,
'PL48BZ',                -- term_postcode,
'345 HOME ROAD',         -- home_address,
'DY15HGL',               -- home_postcode,
'07923584331',           -- mobile_number,
'01562748594',           -- home_number ,
'tom@gmail.com',         -- email_address,
'tom22');                -- username