오라클 자동증가 값 이용하기(auto_increment -> Sequence)
MySQL에서는 테이블 생성시 auto_increment를 이용함으로 자동증가 할 수 있는 명령어가 있습니다..
오라클에서는 이런 편리한 기능을 사용할 수가 없습니다.
하지만 Sequence를 이용함으로 해결하고 auto_increment에서는 할 수 없었던 다음에 사용될 자동증가값 까지 알아 낼 수 있습니다.
방법.
1. 먼저 Sequence를 생성해 줍니다
Create sequence test_num
increment by 1 -- 증가값(1씩증가)
start with 1 -- 시작값(1부터 시작)
nomaxvalue -- 최대값 재한 없음
nocycle
nocache;
2. 테이블을 생성해 줍니다
create table test(id number(4), name varchar2(10));
3. 자동 증가값 이용해서 데이터 삽입
insert into test(num) values (test_num.nextval);
4. 현재 자동증가값 읽어 오기
select 시퀀스명.currval from dual;
5. 시퀀스 삭제
drop sequence test_num;
* NEXTVAL, CURRVAL을 사용할 수 없는 경우
- view의 select절
- distinct 키워드가 있는 select문
- group by, having, order by절이 있는 select문
- select, delete, update의 subquery
- create table, alter table 명령의 default값
* NEXTVAL, CURRVAL을 사용할 수 있는 경우
- subquery가 아닌 select문
- insert문의 select절
- insert문의 value절
- update문의 set절