十五、Oracle學習筆記:序列(用於表字段值自增)
阿新 • • 發佈:2019-02-06
一、序列
1.序列是資料庫中為資料表提供的可以自動生成的唯一數值, 通常用來給主鍵欄位賦值。可以遞增或者遞減。作為主鍵的欄位,通常不人為賦值,需要使用序列自動生成的值。
2.序列關鍵字 sequence 序列和表一樣,都是資料庫中的物件。通常序列為一張表提供主鍵值。也可以為多張表的主鍵提供主鍵值。
3.序列的建立
create sequence seqName
[start with i] -- 從i開始 不指定時預設從1開始
[increment by j]-- 每次遞增或遞減j/ 預設遞增1, j:為正值時,表示遞增為負值時,表示遞減
[maxvalue m|nomaxvalue]--表示最大值m
[minvalue n|nominvalue]--表示最小值n
[cycle|nocycle]--表示迴圈|不迴圈
[cache n|nocache]--表示快取n個數. 預設儲存20個數。
--練習:建立序列 seq_emp 從 10000開始,每次增加10,最大值10100,最小值 9900 可迴圈。
create sequence seq_emp start with 10000 increment by 10 maxvalue 10100 minvalue 9900 cycle;
4.序列中的兩個偽列。
nextval:下一個值。
currval: 當前值,此偽列只有在使用了nextval偽列後,才可以使用。
select seq_emp.nextval from dual;
select seq_emp.currval from dual;
二、序列的綜合來使用
--練習:建立表 employee 欄位empno,number(4) 設計成主鍵約束,ename,varchar(20),非空約sal,number(9,2) drop table employee; create table employee ( empno number(4) primary key, ename varchar2(20) not null, sal number(9,2) ); --建立序列 seq_employee 從1000開始,每次增加1,插入資料,模擬3條 drop sequence seq_employee; create sequence seq_employee start with 1000; select seq_employee.nextval from dual; select seq_employee.currval from dual; insert into employee values(seq_employee.nextval,'張三',3000); insert into employee values(seq_employee.nextval,'李四',4000); insert into employee values(seq_employee.nextval,'王五',5000); commit; select * from employee;