2.2.2. Primary Tables

Now let us proceed to the primary tables. The first will be the CUSTOMER table. We will create a sequence (a generator) for its primary key and a corresponding trigger for implementing it as an auto-incrementing column. We will do the same for each of the tables.

  1. CREATE GENERATOR GEN_CUSTOMER_ID;
  2. CREATE TABLE CUSTOMER (
  3. CUSTOMER_ID INTEGER NOT NULL,
  4. NAME VARCHAR(60) NOT NULL,
  5. ADDRESS VARCHAR(250),
  6. ZIPCODE D_ZIPCODE,
  7. PHONE VARCHAR(14),
  8. CONSTRAINT PK_CUSTOMER PRIMARY KEY (CUSTOMER_ID)
  9. );
  10. SET TERM ^ ;
  11. CREATE OR ALTER TRIGGER CUSTOMER_BI FOR CUSTOMER
  12. ACTIVE BEFORE INSERT POSITION 0
  13. AS
  14. BEGIN
  15. IF (NEW.CUSTOMER_ID IS NULL) THEN
  16. NEW.CUSTOMER_ID = NEXT VALUE FOR GEN_CUSTOMER_ID;
  17. END
  18. ^
  19. SET TERM ; ^
  20. COMMENT ON TABLE CUSTOMER IS
  21. 'Customers';
  22. COMMENT ON COLUMN CUSTOMER.CUSTOMER_ID IS
  23. 'Customer Id';
  24. COMMENT ON COLUMN CUSTOMER.NAME IS
  25. 'Name';
  26. COMMENT ON COLUMN CUSTOMER.ADDRESS IS
  27. 'Address';
  28. COMMENT ON COLUMN CUSTOMER.ZIPCODE IS
  29. 'Zip Code';
  30. COMMENT ON COLUMN CUSTOMER.PHONE IS
  31. 'Phone';
  • In Firebird 3.0, you can use IDENTITY columns as auto-incremental fields. The script for creating the table would then be as follows:

    1. CREATE TABLE CUSTOMER (
    2. CUSTOMER_ID INTEGER GENERATED BY DEFAULT AS IDENTITY,
    3. NAME VARCHAR(60) NOT NULL,
    4. ADDRESS VARCHAR(250),
    5. ZIPCODE D_ZIPCODE,
    6. PHONE VARCHAR(14),
    7. CONSTRAINT PK_CUSTOMER PRIMARY KEY (CUSTOMER_ID)
    8. );
  • In Firebird 3.0, you need the USAGE privilege to use a sequence (generator), so you will have to add the following line to the script:

    1. GRANT USAGE ON SEQUENCE GEN_CUSTOMER_ID TO TRIGGER CUSTOMER_BI;

Now we construct a script for creating the PRODUCT table:

  1. CREATE GENERATOR GEN_PRODUCT_ID;
  2. CREATE TABLE PRODUCT (
  3. PRODUCT_ID INTEGER NOT NULL,
  4. NAME VARCHAR(100) NOT NULL,
  5. PRICE D_MONEY NOT NULL,
  6. DESCRIPTION BLOB SUB_TYPE 1 SEGMENT SIZE 80,
  7. CONSTRAINT PK_PRODUCT PRIMARY KEY (PRODUCT_ID)
  8. );
  9. SET TERM ^;
  10. CREATE OR ALTER TRIGGER PRODUCT_BI FOR PRODUCT
  11. ACTIVE BEFORE INSERT POSITION 0
  12. AS
  13. BEGIN
  14. IF (NEW.PRODUCT_ID IS NULL) THEN
  15. NEW.PRODUCT_ID = NEXT VALUE FOR GEN_PRODUCT_ID;
  16. END
  17. ^
  18. SET TERM ;^
  19. COMMENT ON TABLE PRODUCT IS
  20. 'Goods';
  21. COMMENT ON COLUMN PRODUCT.PRODUCT_ID IS
  22. 'Product Id';
  23. COMMENT ON COLUMN PRODUCT.NAME IS
  24. 'Name';
  25. COMMENT ON COLUMN PRODUCT.PRICE IS
  26. 'Price';
  27. COMMENT ON COLUMN PRODUCT.DESCRIPTION IS
  28. 'Description';

In Firebird 3.0, you need to add the command for granting the USAGE privilege for a sequence (generator) to the script:

  1. GRANT USAGE ON SEQUENCE GEN_PRODUCT_ID TO TRIGGER PRODUCT_BI;