Q&A

  • 인터베이스 최대값 구하는 방법을...
인터베이스를 사용하는데 초보입니다.
필드의 최대값을 구해서 1씩 증가하는 구현을 알고 싶은데 아무것도 생각이 안나네요.
예제나 간략한 구현방법을 부탁드립니다.
3  COMMENTS
  • Profile
    박정훈 2005.03.12 06:44
    아래 부분을 번역을 해 보심이 ^ㅡ^


    How to create auto increment values?

    For this task, Firebird uses generators (like Oracle). Each generator has a value. Here's an example how to use generators in comparison with MySQL autoinc values:


    MySQL:

    CREATE TABLE test
    (
    field1 integer not null auto_increment,
    field2 char(10),
    PRIMARY KEY (field1)
    );

    inserting values:
    INSERT INTO test (field2) VALUES ('testme');



    Firebird:

    CREATE TABLE test
    (
    field1 integer not null,
    field2 char(10),
    PRIMARY KEY (field1)
    );



    CREATE GENERATOR gen_test_id;

    inserting values:
    INSERT INTO test (field1, field2) VALUES (gen_id(gen_test_id, 1), 'testme');



    This may seem little too complicated, but generators give you much more power than autoinc values, since you can always read generator value without increasing it:



    SELECT gen_id(gen_test_id, 0) FROM ...

    and you can change the current value with:



    SET GENERATOR gen_test_id TO [some_value];



    To make usage of generators easier, you can define trigger for your table. The trigger will automatically insert new generator value each time the row is inserted. Here's an example:



    CREATE TRIGGER test_bi FOR test
    ACTIVE BEFORE INSERT POSITION 0
    AS
    BEGIN
    IF (NEW.field1 IS NULL) THEN
      NEW.field1 = GEN_ID(gen_test_id,1);
    END



    This is even better than autoinc values since you can insert any value into autoinc column if you want to. The generator value will be inserted only if no value is supplied. Many GUI tools for Firebird management have options to automatically create such triggers when you select that you want an autoincrement column.

    To learn more about generators look at the InterBase Data Definition Guide

    In case you didn't know, Firebird is an InterBase 6 fork and almost all InterBase 6 documents apply to it. Alternatively you can get Firebird sepecific documentation by buying a copy of the IBPhoenix CD.

    Is there something like limit x, y in select query?

    Yes, there is, it's named FIRST x SKIP y, and it used like this:



    SELECT FIRST x SKIP y FROM ... [rest of query]



    This will select total of x rows, skipping first y rows (i.e. it starts from row y+1).

    How to list all tables in a database?
  • Profile
    나나나 2005.03.11 22:03





    어디선가 본거 같은데..
    이건 어떤가요?

    Table Name : tbl
    column : aaa int, bbb char(3)
    PK : aaa

    1. 일반
         insert into tbl (aaa, bbb) values (1, '123')

    2. 제안
         insert into tbl (aaa, bbb) select max(aaa) + 1, '123' from tbl
  • Profile
    이중철 2005.03.11 21:52
    CREATE GENERATOR 명칭
    이거 쓰면 될거에요
    쓸때는 GEN_ID(명칭, 1) 이렇게 하면 되고요
    이것이 오라클의 nextval하고 같아요
    현재 파이어버드 연구중이고 파이어버드는 인터베이스에서 기초한 것이니 아마
    인터베이스에서도 있을겁니다.