在一系列数字中触发和序列分配的ID

时间:2015-04-23 16:34:10

标签: sql oracle plsql triggers

我试图在SQL Developer中编写一个触发器,当在Student表中输入某些内容时,会生成一个以" S"在S500和S999之间。

我收到错误

Error report:
Unknown Command

当我尝试编译触发器以生成一个数字时,我无法弄清楚如何使它只生成S500和S999之间的数字(我的尝试在下面的代码中作为注释被删除) )。

这是我第一次写一个触发器,我试图脱离另一个例子(相同的想法,但有员工ID而不是学生ID,没有500-999约束)但我不确定我在哪里出错了。我查找了相关的堆栈溢出问题,但无法找到专门处理500-999部分的问题。

任何想法或帮助将不胜感激!

CREATE OR REPLACE TRIGGER students_seq
  BEFORE INSERT 
  ON STUDENTS 
  FOR EACH ROW
  DECLARE
  temp_studentID students.studentID%type; 
  BEGIN
  SELECT LPAD(to_char(student_seq.nextval), 4, 'S000') INTO temp_studentID FROM 
  dual;
  :new.studentID := temp_studentID;
  -- update_studentID ( some_studentID, 999); want Student IDs to begin with S500 and go to S999
  END;
  /

1 个答案:

答案 0 :(得分:1)

你所展示的作品是用来设置学生ID的顺序(不是我怎么做的,但稍后会详细介绍)。要限制该值,您可以为序列设置最大值:

create sequence student_seq start with 500 maxvalue 999;

然后你可以使用你的触发器,或下面的变种。另外,对不同的对象使用相同的名称会让人感到困惑,所以我会重命名你的触发器。这一切都有效,在SQL Developer中作为脚本运行:

create table students (studentid varchar2(4), name varchar2(20));

create sequence student_seq start with 500 maxvalue 999;

create or replace trigger students_trig
before insert on students 
for each row
begin
  select 'S' || to_char(student_seq.nextval, 'FM000') into :new.studentid
  from dual;
end;
/

或者,如果您使用11g或更高版本,则可以直接分配到该列:

...
begin
  :new.studentid := 'S' || to_char(student_seq.nextval, 'FM000');
end;
/

然后,您可以看到正在使用的值:

insert into students (name) values ('Bob');

1 row inserted.

insert into students (name) values ('Alice');

1 row inserted.

select * from students;

STUDENTID NAME               
--------- --------------------
S500      Bob                 
S501      Alice               

如果我丢弃一大堆序列值到达你的范围的末尾,那么currval是998,那么我只能再插入一行:

insert into students (name) values ('Charlie');

1 row inserted.

insert into students (name) values ('Diane');

SQL Error: ORA-08004: sequence STUDENT_SEQ.NEXTVAL exceeds MAXVALUE and cannot be instantiated
...

select * from students;

STUDENTID NAME               
--------- --------------------
S500      Bob                 
S501      Alice               
S999      Charlie             

您无法创建ID超出范围的学生。您可以定义要回绕到500的序列,但是您必须处理与现有值的冲突。