티스토리 뷰

mariaDB

마리아 db 시퀀스 생성 함수

xemaker 2019. 7. 15. 13:58
마리아 db 10.3 부터는 시퀀스가 있다고 들었는데 현재 10.1을 쓰고 있다.

시퀀스를 써야 하는데...

구글링 해봤는데 잘 안되고 삽질한 후 최종 되는 버전으로 올려보겠다.

먼저 채번 테이블 작성

create table A_SEQUENCE (
SEQ bigint(64) not null auto_increment primary key
)
collate='utf8_general_ci'
ENGINE=InnoDB
;

그 다음 시퀀스 함수 생성

delimiter //

drop function if exists F_SEQ;

create function F_SEQ() returns bigint

begin
declare x bigint;
insert into A_SEQUENCE(seq) values(0);
select last_insert_id() into x;

if(x%10000=0) then
delete from A_SEQUENCE where seq <x;
end if;

return x;
end

//


저렇게 하면 0 duplicate 오류가 난다. 그래서 test 컬럼을 1개 만들어 거기에다가 insert 를 한다.

insert into A_SEQUENCE(test) values(0)

안되서 별 쌩쑈를 다 했는데 결국은
if(x%10000=0) then
delete from A_SEQUENCE where seq <x;
이부분이 문제 였다. 아놔 인터넷 보고 했는디..
삭제 하니까 된다.


여기서 중요한것.
사용중 이관을 할 경우에 문제가 생길 수 있다.

다 지우고 해야 되지 않을까

last_insert_id 는 connection specific 이란다. 커넥션마다 다르다는 얘기? 이관등 작업할때 사용에 주의 해야 할듯.

Removing all the elements in a table does not affect the primary key. The primary key will still autoincrement from its last value.
If you want to reset the primary key, you can try to truncate the table:
TRUNCATE TABLE yourtable;
This clears all the elements from yourtable. Whether it resets the primary key depends on your database. With Mysql it should work, as Mysql deletes and recreates the table on TRUNCATE.

https://stackoverflow.com/questions/10753505/mysql-id-auto-increment-doesnt-starts-from-0
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함