오라클에서는 존재하는 시퀀스를 사용했는데 MYSQL은 시퀀스가 존재하지 않는다. 따라서 새로운 테이블을 생성하여 그 테이블이 시퀀스 역할을 하도록 해야한다. 시퀀스는 보통 중복되지 않는 증가 숫자로 Primary key 역활을 한다.
- 시퀀스 저장할 테이블 생성
create table sequences(
name varchar(32),
currval bigint unsigned
)engine=InnoDB;
- 시퀀스 생성
-- 시퀀스를 생성하는 프로시저 생성
delimiter $$
create procedure create_sequence(in the_name text)
modifies sql data
deterministic
begin
delete from sequences where name=the_name;
insert into sequences values(the_name, 0);
end$$
create function nextval(the_name varchar(32)) returns bigint unsigned
modifies sql data
deterministic
begin
declare ret bigint unsigned;
update sequences set currval = currval+1 where name = the_name;
select currval into ret from sequences where name = the_name limit 1;
return ret;
end$$
delimiter ;
- 시퀀스 사용
INSERT INTO SEQUENCES VALUES('gon','1');
-- NEXTVAL 값을 가져오기
SELECT * FROM SEQUENCES;
SELECT NEXTVAL('gon')
FROM DUAL;
SELECT * FROM sequences;
SET SQL_SAFE_UPDATES = 0;
- 함수 1개로 변형
-- sequence table create
create table sequences(
currval bigint unsigned,
name varchar(32),
primary key(currval)
)engine=InnoDB;
-- 함수 1개로 데이터 삽입하면 자동으로 시퀀스 생성되도록 함수 수정
delimiter $$
create function nextval(the_name varchar(32)) returns bigint unsigned
modifies sql data
deterministic
begin
declare ret bigint unsigned;
declare tmp varchar(50);
select name into tmp
from sequences
where name = the_name;
select MAX(currval) into ret
from sequences;
if tmp is null then
insert into sequences values(ret+1, the_name);
end if;
return ret+1;
end$$
delimiter ;
drop table sequences;
drop function if exists nextval;
-- 안전모드 해제
SET SQL_SAFE_UPDATES = 0;
-- 함수 1개로 데이터 삽입하면 자동으로 시퀀스 생성되도록 함수 수정(Insert 처음 한 번 필수)
INSERT INTO sequences VALUES(0,"KEY");
SELECT NEXTVAL("D");
SELECT * FROM sequences;