프로그래밍 노트

Firebird에서 auto_increment 같은 자동 연번 field 사용하기 본문

데이터베이스/Firebird

Firebird에서 auto_increment 같은 자동 연번 field 사용하기

떡잎 2011. 2. 9. 16:32



Firebird의 Firebird ISQL Tool을 실행해서 아래 녹색 상자의 Source를 전체를 붙여 넣어보면 어떻게 동작하는지 대충 알 수 있다.

create database 'TestAutoNoDb.fdb' user 'sysdba' password 'masterkey';

set autoddl off;

create table AutoNoTable (
  AutoId   integer not null,
  Fld_Int  integer,
  Fld_Char char(200),
 
  constraint pk_AutoNoTable primary key (AutoId)
);

create generator gen_AutoId;

set term ^;

create trigger trg_AutoNoTable_SeqNo for AutoNoTable
active before insert position 1
AS
begin
  if (new.AutoId is null) then
    new.AutoId = gen_id(gen_AutoId, 1);
end
^
commit work^

set term ; ^

insert into AutoNoTable (Fld_Int, Fld_Char) values (1, 'one');
insert into AutoNoTable (Fld_Int, Fld_Char) values (2, 'two');
insert into AutoNoTable (Fld_Int, Fld_Char) values (3, 'three');

commit work;

select * from AutoNoTable;



설명

// Database 만들기
create database 'TestAutoNoDb.fdb' user 'sysdba' password 'masterkey';

// 자동 Commit mode off(?)
set autoddl off;

// 자동 연번 Test용 Table 만들기
create table AutoNoTable (
  AutoId   integer not null,
  Fld_Int  integer,
  Fld_Char char(200),
 
  constraint pk_AutoNoTable primary key (AutoId)
);

// 자동 연번용 generator 만들기
create generator gen_AutoId;

// 자동 연번 Trigger 만들기
set term ^;

create trigger trg_AutoNoTable_SeqNo for AutoNoTable
active before insert position 1
AS
begin
  if (new.AutoId is null) then
    new.AutoId = gen_id(gen_AutoId, 1);
end
^
commit work^

// 데이터 추가
set term ; ^

insert into AutoNoTable (Fld_Int, Fld_Char) values (1, 'one');
insert into AutoNoTable (Fld_Int, Fld_Char) values (2, 'two');
insert into AutoNoTable (Fld_Int, Fld_Char) values (3, 'three');

commit work;

// 데이터 가져오기
select * from AutoNoTable;


실행 결과

      AUTOID      FLD_INT FLD_CHAR
============ ============ ===========
          1            1 one
           2            2 two
           3            3 three

AUTOID와 추가 하지 않아도 자동으로 연번이 생성됨

주의) 이 트리거에 문제점이 하나 있다.
연번이 가장 큰 숫자에서 시작하지 않는다. -.-;;
그래서 이 트리거를 사용하지 않고 인위적으로 AUTOID field에 높은 번호를 입력하면
자동으로 AutoID가 입력될 때 같은 번호가 나오면 Error가 발생되게 된다.


-----------------------------------------

참고

위 Source를 Firebird ISQL Tool에 붙이려면 Firebird ISQL Tool의 Caption bar에서 오른쪽 click하면 popup menu가 표시되고 편집 > 붙여넣기(P)를 선택하면 된다.

Comments