1 분 소요

시퀀스(sequence)

 

연속적인 번호를 만들어주는 객체 (일련번호 생성 객체)

mysql의 auto_increment를 대체하는 기능의 객체

 

구문 형식

create sequence (시퀀스 이름)
    incrementby n -> 시퀀스 번호의 증가값을 설정한다.(default 1)
startwith n -> 시작값 설정(default 1)
maxvalue n | nomaxvalue <- 시퀀스 최대값 설정
minvalue n | nominvalue <- 시퀀스 최소값 설정 : cycle 옵션일 경우 시작값
cycle | nocycle <- 최대값을 지나면 최소값으로 순환되는 옵션 설정
cache n | nocache <- 시퀀스의 값을 메모리에 저장
create table c_dept
as
select * from departments
where 1 = 0;
insert into c_dept
values(seq_dept.nextval, 'database',100,200);
DEPARTMENT_ID	DEPARTMENT_NAME	MANAGER_ID	LOCATION_ID
20	database	100	200
30	database	100	200
40	database	100	200

 

시퀀스 생성

create sequence seq_dept
increment by 10
start with 10
minvalue 0
nocycle;

 

시퀀스 확인하기

select*from user_sequences;
SEQUENCE_NAME	MIN_VALUE	MAX_VALUE	INCREMENT_BY	CYCLE_FLAG	ORDER_FLAG	CACHE_SIZE	LAST_NUMBER
DEPARTMENTS_SEQ	1	9990	10	N	N	0	280
EMPLOYEES_SEQ	1	9999999999999999999999999999	1	N	N	0	207
LOCATIONS_SEQ	1	9900	100	N	N	0	3300
SEQ_DEPT	0	99	3	Y	N	20	23

 

시퀀스 삭제하기

drop sequence seq_dept;
Sequence SEQ_DEPT() 삭제되었습니다.

 

시퀀스 새로운 번호(일련번호)만들기: 한번 발급된 번호는 다시 발급 되지 않는다

nextval: 다음번호

select seq_dept.nextval from dual;
NEXTVAL
10
NEXTVAL
20

 

  • currval: 현재 번호
select seq_dept.currval from dual;
CURRVAL
20

 

데이터베이스의 객체를 변경

create table c_dept
as
select * from departments
where 1 = 0;
insert into c_dept
values(seq_dept.nextval, 'database', 100, 200);
alter sequence seq_dept
increment by 3
maxvalue 99
cycle;
select seq_dept.currval from dual;
CURRVAL
58

 

select seq_dept.nextval from dual;
NEXTVAL
58

 

insert into c_dept
values(seq_dept.nextval, 'database', 100, 200
DEPARTMENT_ID	DEPARTMENT_NAME	MANAGER_ID	LOCATION_ID
6	database	100	200
40	database	100	200
58	database	100	200

 

제품 번호를 생성하는 시퀀스 만들기

create sequence seq_product
start with 100
increment by 1
create table product(
    prod_id number(3),
    prod_name varchar2(20)
);

 

select seq_product.nextval from dual;
insert into product values(seq_product.currval, '상품1');

insert into product values(seq_product.nextval, '상품2');

insert into product values(seq_product.nextval, '상품3');
PROD_ID	PROD_NAME
101	상품3
102	상품2
102	상품1
108	상품2

카테고리:

업데이트:

댓글남기기