DB2 for z/OS - Identity columns - Colunas de identidade


Volta a página anterior

Volta ao Menu Principal


Desenvolvido por DORNELLES, Carlos Alberto - Analista de Sistemas - Brasília DF. - cad_cobol@hotmail.com

DB2 for z/OS - Identity columns - Colunas de identidade

An identity column contains a unique numeric value for each row in the table.
Db2 can automatically generate sequential numeric values for this column as rows are inserted into the table.
Thus, identity columns are ideal for primary key values, such as employee numbers or product numbers.

Uma coluna de identidade contém um valor numérico exclusivo para cada linha da tabela.
O Db2 pode gerar automaticamente valores numéricos sequenciais para esta coluna conforme as linhas são inseridas na tabela. Portanto, as colunas de identidade são ideais para valores de chave primária, como números de funcionários ou números de produtos.

Using identity columns as keys - Usando colunas de identidade como chaves

If you define a column with the AS IDENTITY attribute, and with the GENERATED ALWAYS and NO CYCLE attributes, Db2 automatically generates a monotonically increasing or decreasing sequential number for the value of that column when a new row is inserted into the table.
However, for Db2 to guarantee that the values of the identity column are unique, you should define a unique index on that column.

Se você definir uma coluna com o atributo AS IDENTITY e com os atributos GENERATED ALWAYS e NO CYCLE, o Db2 gera automaticamente um número sequencial monotonicamente crescente ou decrescente para o valor dessa coluna quando uma nova linha é inserida na tabela.
No entanto, para que o Db2 garanta que os valores da coluna de identidade sejam exclusivos, você deve definir um índice exclusivo nessa coluna.

You can use identity columns for primary keys that are typically unique sequential numbers, for example, order numbers or employee numbers.
By doing so, you can avoid the concurrency problems that can result when an application generates its own unique counter outside the database.

Você pode usar colunas de identidade para chaves primárias que normalmente são números sequenciais exclusivos, por exemplo, números de pedidos ou números de funcionários.
Fazendo isso, você pode evitar os problemas de simultaneidade que podem resultar quando um aplicativo gera seu próprio contador exclusivo fora do banco de dados.

Recommendation: - Recomendação:

Set the values of the foreign keys in the dependent tables after loading the parent table.
If you use an identity column as a parent key in a referential integrity structure, loading data into that structure could be quite complicated.
The values for the identity column are not known until the table is loaded because the column is defined as GENERATED ALWAYS.

Defina os valores das chaves estrangeiras nas tabelas dependentes após carregar a tabela pai.
Se você usar uma coluna de identidade como uma chave pai em uma estrutura de integridade referencial, carregar dados nessa estrutura pode ser bastante complicado.
Os valores para a coluna de identidade não são conhecidos até que a tabela seja carregada porque a coluna está definida como GENERATED ALWAYS.

You might have gaps in identity column values for the following reasons:

Você pode ter lacunas nos valores da coluna de identidade pelos seguintes motivos:

  • If other applications are inserting values into the same identity column
    Se outros aplicativos estão inserindo valores na mesma coluna de identidade

  • If Db2 terminates abnormally before it assigns all the cached values
    Se o Db2 terminar de forma anormal antes de atribuir todos os valores em cache

  • If your application rolls back a transaction that inserts identity values
    Se o seu aplicativo reverter uma transação que insere valores de identidade

Defining an identity column - Definindo uma coluna de identidade

You can define an identity column as either GENERATED BY DEFAULT or GENERATED ALWAYS:
Você pode definir uma coluna de identidade como GENERATED BY DEFAULT ou GENERATED ALWAYS:

  • If you define the column as GENERATED BY DEFAULT, you can insert a value, and Db2 provides a default value if you do not supply one.
    Se você definir a coluna como GENERATED BY DEFAULT, poderá inserir um valor e o Db2 fornecerá um valor padrão se você não fornecer um.

  • If you define the column as GENERATED ALWAYS, Db2 always generates a value for the column, and you cannot insert data into that column.
    If you want the values to be unique, you must define the identity column with GENERATED ALWAYS and NO CYCLE and define a unique index on that column.
    Se você definir a coluna como GENERATED ALWAYS, o Db2 sempre gera um valor para a coluna e você não pode inserir dados nessa coluna.
    Se quiser que os valores sejam exclusivos, você deve definir a coluna de identidade com GENERATED ALWAYS e NO CYCLE e definir um índice exclusivo nessa coluna.

The values that Db2 generates for an identity column depend on how the column is defined.
The START WITH option determines the first value that Db2 generates.
The values advance by the INCREMENT BY value in ascending or descending order.

Os valores que o Db2 gera para uma coluna de identidade dependem de como a coluna é definida.
A opção START WITH determina o primeiro valor gerado pelo Db2.
Os valores avançam pelo valor de INCREMENT BY em ordem crescente ou decrescente.

The MINVALUE and MAXVALUE options determine the minimum and maximum values that Db2 generates.
However, the The CYCLE or NO CYCLE option determines whether Db2 wraps values when it has generated all values between the START WITH value and MAXVALUE if the values are ascending, or between the START WITH value and MINVALUE if the values are descending.
MINVALUE and MAXVALUE do not constrain a START WITH or RESTART WITH value.

As opções MINVALUE e MAXVALUE determinam os valores mínimo e máximo que o Db2 gera.
No entanto, a opção The CYCLE ou NO CYCLE determina se o Db2 agrupa os valores quando gera todos os valores entre o valor START WITH e MAXVALUE se os valores forem ascendentes ou entre o valor START WITH e MINVALUE se os valores forem descendentes.
MINVALUE e MAXVALUE não restringem um valor START WITH ou RESTART WITH.

Example: Using GENERATED ALWAYS and CYCLE - Exemplo: Usando GENERATED ALWAYS e CYCLE

Suppose that table T1 is defined with GENERATED ALWAYS and CYCLE:
Suponha que a tabela T1 seja definida com GENERATED ALWAYS e CYCLE:

CREATE TABLE T1
  (CHARCOL1 CHAR(1),
   IDENTCOL1 SMALLINT GENERATED ALWAYS AS IDENTITY
     (START WITH -1,
      INCREMENT BY 1,
      CYCLE,
      MINVALUE -3,
      MAXVALUE 3));

Now suppose that you execute the following INSERT statement eight times:
Agora, suponha que você execute a seguinte instrução INSERT oito vezes:

INSERT INTO T1 (CHARCOL1) VALUES ('A');

When Db2 generates values for IDENTCOL1, it starts with -1 and increments by 1 until it reaches the MAXVALUE of 3 on the fifth INSERT.
To generate the value for the sixth INSERT, Db2 cycles back to MINVALUE, which is -3.
T1 looks like this after the eight INSERT statements are executed:

Quando o Db2 gera valores para IDENTCOL1, ele começa com -1 e aumenta em 1 até atingir MAXVALUE de 3 no quinto INSERT.
Para gerar o valor para o sexto INSERT, Db2 volta para MINVALUE, que é -3.
T1 fica assim depois que as oito instruções INSERT são executadas:

CHARCOL1  IDENTCOL1
========  =========
A                -1
A                 0
A                 1
A                 2
A                 3
A                -3
A                -2
A                -1

The value of IDENTCOL1 for the eighth INSERT repeats the value of IDENTCOL1 for the first INSERT.
O valor de IDENTCOL1 para o oitavo INSERT repete o valor de IDENTCOL1 para o primeiro INSERT.

Example: START WITH or RESTART WITH values outside the range for cycling - Exemplo: START WITH ou RESTART WITH valores fora do intervalo para ciclismo

The MINVALUE and MAXVALUE options do not constrain the START WITH value.
That is, the START WITH clause can be used to start the generation of values outside the range that is used for cycles.
However, the next generated value after the specified START WITH value is MNVALUE for an ascending identity column or MAXVALUE for a descending identity column.
The same is true if you alter the identity column and specify a RESTART WITH value.

As opções MINVALUE e MAXVALUE não restringem o valor START WITH.
Ou seja, a cláusula START WITH pode ser usada para iniciar a geração de valores fora da faixa que é usada para ciclos.
No entanto, o próximo valor gerado após o valor START WITH especificado é MNVALUE para uma coluna de identidade crescente ou MAXVALUE para uma coluna de identidade decrescente.
O mesmo é verdadeiro se você alterar a coluna de identidade e especificar um valor RESTART WITH.

Consider T1 from the previous example, and suppose that you alter the table with a statement that specifies the following keywords.
Considere T1 do exemplo anterior e suponha que você altere a tabela com uma instrução que especifica as seguintes palavras-chave.

ALTER TABLE T1 
  ALTER COLUMN IDENTCOL1 SET GENERATED ALWAYS RESTART WITH 99;

Now suppose that you execute the following INSERT statement three times:
Agora, suponha que você execute a seguinte instrução INSERT três vezes:

INSERT INTO T1 (CHARCOL1) VALUES ('B');

When Db2 generates the IDENTCOL1 value, it starts with 99.
However, for the next generated value, Db2 again cycles back to MINVALUE, which is -3.
T1 looks like this after the three INSERT statements are executed:

Quando Db2 gera o valor IDENTCOL1, ele começa com 99.
No entanto, para o próximo valor gerado, Db2 volta novamente para MINVALUE, que é -3.
T1 fica assim depois que as três instruções INSERT são executadas:

CHARCOL1  IDENTCOL1
========  =========
A                -1
A                 0
A                 1
A                 2
A                 3
A                -3
A                -2
A                -1
B                99
B                -3
B                -2

Identity columns as primary keys - Colunas de identidade como chaves primárias

The SELECT from INSERT statement enables you to insert a row into a parent table with its primary key defined as a Db2-generated identity column, and retrieve the value of the primary or parent key.
You can then use this generated value as a foreign key in a dependent table.

A instrução SELECT de INSERT permite inserir uma linha em uma tabela pai com sua chave primária definida como uma coluna de identidade gerada pelo Db2 e recuperar o valor da chave primária ou pai.
Você pode então usar este valor gerado como uma chave estrangeira em uma tabela dependente.

In addition, you can use the IDENTITY_VAL_LOCAL function to return the most recently assigned value for an identity column.
Além disso, você pode usar a função IDENTITY_VAL_LOCAL para retornar o valor atribuído mais recentemente para uma coluna de identidade.

Example: Using SELECT from INSERT - Exemplo: Usando SELECT de INSERT

Suppose that an EMPLOYEE table and a DEPARTMENT table are defined in the following way:
Suponha que uma tabela EMPLOYEE e uma tabela DEPARTMENT sejam definidas da seguinte maneira:

CREATE TABLE EMPLOYEE
  (EMPNO      INTEGER GENERATED ALWAYS AS IDENTITY
              PRIMARY KEY NOT NULL,
   NAME       CHAR(30) NOT NULL,
   SALARY     DECIMAL(7,2) NOT NULL,
   WORKDEPT   SMALLINT);

CREATE TABLE DEPARTMENT
  (DEPTNO     SMALLINT NOT NULL PRIMARY KEY,
   DEPTNAME   VARCHAR(30),
   MGRNO      INTEGER NOT NULL,
   CONSTRAINT REF_EMPNO FOREIGN KEY (MGRNO)
     REFERENCES EMPLOYEE (EMPNO) ON DELETE RESTRICT);

ALTER TABLE EMPLOYEE ADD
  CONSTRAINT REF_DEPTNO FOREIGN KEY (WORKDEPT)
     REFERENCES DEPARTMENT (DEPTNO) ON DELETE SET NULL;

When you insert a new employee into the EMPLOYEE table, to retrieve the value for the EMPNO column, you can use the following SELECT from INSERT statement:
Ao inserir um novo funcionário na tabela EMPLOYEE, para recuperar o valor da coluna EMPNO, você pode usar a seguinte instrução SELECT a partir de INSERT:

EXEC SQL 
  SELECT EMPNO INTO :hv_empno
    FROM FINAL TABLE (INSERT INTO EMPLOYEE (NAME, SALARY, WORKDEPT)
                      VALUES ('New Employee', 75000.00, 11));

The SELECT statement returns the Db2-generated identity value for the EMPNO column in the host variable :hv_empno.
A instrução SELECT retorna o valor de identidade gerado pelo Db2 para a coluna EMPNO na variável do host: hv_empno.

You can then use the value in :hv_empno to update the MGRNO column in the DEPARTMENT table with the new employee as the department manager:
Você pode então usar o valor em :hv_empno para atualizar a coluna MGRNO na tabela DEPARTAMENT com o novo funcionário como gerente de departamento:

EXEC SQL 
  UPDATE DEPARTMENT 
     SET MGRNO = :hv_empno
   WHERE DEPTNO = 11;


© Copyright IBM Corp.