delphifirebirdauto-incrementunidac

Create table and auto increment column in Firebird with Delphi


I want to create table in Firebird embedded and set a column for auto increment, but I can't. I can create the table, but can't set a column for auto increment.

I am using:
Firebird embedded 2.5
Delphi xe3
UniDAC Componnent

my SQL command:

with UniSQL1 do
  begin
    SQL.Text := 'Create TABLE tab1(EMP_NO EMPNO NOT NULL, '+
  'FIRST_NAME           "FIRSTNAME" NOT NULL, '+
  'LAST_NAME             "LASTNAME" NOT NULL, '+
  'PHONE_EXT                VARCHAR(     4)  COLLATE NONE, '+
 'PRIMARY KEY (EMP_NO) '+
  '); '+
  'CREATE GENERATOR gen_tab1_EMP_NO; '+
  'SET GENERATOR gen_tab1_EMP_NO TO 0; '+
  'SET TERM !! ; '+
  'CREATE TRIGGER SET_EMP_NO FOR tab1 ACTIVE BEFORE INSERT POSITION 0 AS '+
  'BEGIN '+
      'if (new.emp_no is null) then '+
      'new.emp_no = gen_id(gen_tab1_EMP_NO, 1); '+
  'END !!'+
  'SET TERM ; !!';

    try
       Execute;
       ShowMessage('Table Created');
    except
       ShowMessage('Table Not Created');
    end;
  end;

Solution

  • Try this and see where occurs error. You can try too save your script and execute on IBExpert or other tool and see if run properly.

    with UniSQL1 do
    begin
        SQL.Clear;
        SQL.Add('Create TABLE tab1(');
        SQL.Add(     EMP_NO EMPNO NOT NULL,');
        SQL.Add('    FIRST_NAME "FIRSTNAME" NOT NULL,');
        SQL.Add('    LAST_NAME  "LASTNAME" NOT NULL,');
        SQL.Add('    PHONE_EXT  VARCHAR(4) COLLATE NONE,');
        SQL.Add('    PRIMARY KEY (EMP_NO)');
        SQL.Add(')');
        try
            Execute;
        except
            on E:Exception do
                raise Exception.Create('ERROR 1:' + sLineBreak + E.Message);
        end;
    
        SQL.Clear;
        SQL.Add('CREATE GENERATOR gen_tab1_EMP_NO;');
        try
            Execute;
        except
            on E:Exception do
                raise Exception.Create('ERROR 2:' + sLineBreak + E.Message);
        end;
    
        SQL.Clear;
        SQL.Add('SET GENERATOR gen_tab1_EMP_NO TO 0;');
        try
            Execute;
        except
            on E:Exception do
                raise Exception.Create('ERROR 3:' + sLineBreak + E.Message);
        end;
    
        SQL.Clear;
        SQL.Add('CREATE TRIGGER SET_EMP_NO FOR tab1 ACTIVE BEFORE INSERT POSITION 0 AS');
        SQL.Add('BEGIN');
        SQL.Add('    if (new.emp_no is null) then');
        SQL.Add('        new.emp_no = gen_id(gen_tab1_EMP_NO, 1);');
        SQL.Add('END'
        try
            Execute;
        except
            on E:Exception do
                raise Exception.Create('ERROR 4:' + sLineBreak + E.Message);
        end;
    end;