|
Para alguns aplicativos, você pode usar o valor de uma coluna ROWID para navegar diretamente para uma linha.
For some applications, you can use the value of a ROWID column to navigate directly to a row.
Antes de você começar - Before you begin
Certifique-se de que a consulta se qualifique para acesso direto à linha.
Para se qualificar, a condição de pesquisa deve ser um termo booleano, predicado de estágio 1 que se encaixa em um dos seguintes critérios:
Ensure that the query qualifies for direct row access.
To qualify, the search condition must be a Boolean term, stage 1 predicate that fits one of the following criteria:
Sobre esta tarefa - About this task
Conceitos introdutórios - Introductory concepts
Uma coluna ROWID identifica exclusivamente cada linha em uma tabela.
Com colunas ROWID, você pode escrever consultas que navegam diretamente para uma linha na tabela porque a coluna contém implicitamente a localização da linha.br<>
Você pode definir uma coluna ROWID como GENERATED BY DEFAULT ou GENERATED ALWAYS:
A ROWID column uniquely identifies each row in a table.
With ROWID columns you can write queries that navigate directly to a row in the table because the column implicitly contains the location of the row.
You can define a ROWID column as either GENERATED BY DEFAULT or GENERATED ALWAYS:
- Se você definir a coluna como GERADA POR PADRÃO, você pode inserir um valor.
Db2 fornece um valor padrão se você não fornecer um.
No entanto, para poder inserir um valor explícito (usando a instrução INSERT com a cláusula VALUES), você deve criar um índice exclusivo nessa coluna.
If you define the column as GENERATED BY DEFAULT, you can insert a value.
Db2 provides a default value if you do not supply one.
However, to be able to insert an explicit value (by using the INSERT statement with the VALUES clause), you must create a unique index on that column.
- Se você definir a coluna como GENERATED ALWAYS (que é o padrão), o Db2 sempre gerará um valor exclusivo para a coluna.
Você não pode inserir dados nessa coluna. Nesse caso, o Db2 não requer um índice para garantir valores únicos.
If you define the column as GENERATED ALWAYS (which is the default), Db2 always generates a unique value for the column.
You cannot insert data into that column. In this case, Db2 does not require an index to guarantee unique values.
Quando você seleciona uma coluna ROWID, o valor contém implicitamente a localização da linha recuperada.
Se você usar o valor da coluna ROWID na condição de pesquisa de uma consulta subsequente, o Db2 pode escolher navegar diretamente para essa linha.
When you select a ROWID column, the value implicitly contains the location of the retrieved row.
If you use the value from the ROWID column in the search condition of a subsequent query, Db2 can choose to navigate directly to that row.
Se você definir uma coluna em uma tabela para ter o tipo de dados ROWID, o Db2 fornecerá um valor exclusivo para cada linha na tabela apenas se você definir a
coluna como GENERATED ALWAYS.
O objetivo do valor na coluna ROWID é identificar exclusivamente as linhas na tabela.
If you define a column in a table to have the ROWID data type, Db2 provides a unique value for each row in the table only if you define the column as
GENERATED ALWAYS.
The purpose of the value in the ROWID column is to uniquely identify rows in the table.
Você pode usar uma coluna ROWID para escrever consultas que navegam diretamente para uma linha, o que pode ser útil em situações onde o alto desempenho é um
requisito.
Essa navegação direta, sem usar um índice ou varrer o espaço de tabela, é chamada de acesso direto à linha. Além disso, uma coluna ROWID é um requisito para tabelas
que contêm colunas LOB.
Este tópico discute o uso de uma coluna ROWID no acesso direto à linha.
You can use a ROWID column to write queries that navigate directly to a row, which can be useful in situations where high performance is a requirement.
This direct navigation, without using an index or scanning the table space, is called direct row access. In addition, a ROWID column is a requirement for tables
that contain LOB columns.
This topic discusses the use of a ROWID column in direct row access.
Exemplo: - Example:
Suponha que uma tabela EMPLOYEE seja definida da seguinte maneira:
Suppose that an EMPLOYEE table is defined in the following way:
CREATE TABLE EMPLOYEE
(EMP_ROWID ROWID NOT NULL GENERATED ALWAYS
, EMPNO SMALLINT
, NAME CHAR(30)
, SALARY DECIMAL(7,2)
, WORKDEPT SMALLINT);
O código a seguir usa a instrução SELECT de INSERT para recuperar o valor da coluna ROWID de uma nova linha inserida na tabela EMPLOYEE.
Esse valor é então usado para fazer referência a essa linha para a atualização da coluna SALARY.
The following code uses the SELECT from INSERT statement to retrieve the value of the ROWID column from a new row that is inserted into the EMPLOYEE table.
This value is then used to reference that row for the update of the SALARY column.
EXEC SQL BEGIN DECLARE SECTION;
SQL TYPE IS ROWID hv_emp_rowid;
short hv_dept, hv_empno;
char hv_name[30];
decimal(7,2) hv_salary;
EXEC SQL END DECLARE SECTION;
EXEC SQL
SELECT EMP_ROWID
INTO :hv_emp_rowid
FROM FINAL TABLE
(INSERT INTO EMPLOYEE
VALUES (DEFAULT
, :hv_empno
, :hv_name
, :hv_salary
, :hv_dept));
EXEC SQL
UPDATE EMPLOYEE
SET SALARY = SALARY + 1200
WHERE EMP_ROWID = :hv_emp_rowid;
EXEC SQL COMMIT;
Para que o Db2 possa usar o acesso direto à linha para a operação de atualização, a instrução SELECT from INSERT e a instrução UPDATE devem ser executadas na mesma
unidade de trabalho.
Alternativamente, você pode usar uma instrução SELECT from MERGE.
A instrução MERGE executa as operações INSERT e UPDATE como uma instrução coordenada.
For Db2 to be able to use direct row access for the update operation, the SELECT from INSERT statement and the UPDATE statement must execute within the same unit
of work.
Alternatively, you can use a SELECT from MERGE statement.
The MERGE statement performs INSERT and UPDATE operations as one coordinated statement.
Requerimento: - Requirement:
Para usar o acesso direto à linha, você deve usar um valor ROWID recuperado antes de confirmar.
Quando seu aplicativo é confirmado, ele libera sua reivindicação no espaço de tabela.
Após a confirmação, se um REORG for executado em seu espaço de tabela, a localização física das linhas pode mudar.
To use direct row access, you must use a retrieved ROWID value before you commit.
When your application commits, it releases its claim on the table space.
After the commit, if a REORG is run on your table space, the physical location of the rows might change.
Restrição: - Restriction:
Em geral, você não pode usar uma coluna ROWID como uma chave que deve ser usada como um único valor de coluna em várias tabelas.
O valor ROWID para uma linha específica em uma tabela pode mudar com o tempo devido a um REORG do espaço de tabela.
Em particular, você não pode usar uma coluna ROWID como parte de uma chave pai ou chave estrangeira.
In general, you cannot use a ROWID column as a key that is to be used as a single column value across multiple tables.
The ROWID value for a particular row in a table might change over time due to a REORG of the table space.
In particular, you cannot use a ROWID column as part of a parent key or foreign key.
O valor que você recupera de uma coluna ROWID é um valor de caractere de comprimento variável que não é monotonicamente crescente ou decrescente (o valor nem
sempre aumenta ou diminui).
Portanto, uma coluna ROWID não fornece valores adequados para muitos tipos de chaves de entidade, como números de pedidos ou números de funcionários.
The value that you retrieve from a ROWID column is a varying-length character value that is not monotonically ascending or descending (the value is not always
increasing or not always decreasing).
Therefore, a ROWID column does not provide suitable values for many types of entity keys, such as order numbers or employee numbers.
Procedimento - Procedure
Para especificar o acesso direto à linha usando valores ROWID:
To specify direct row access by using ROWID values:
Chame a função interna RID na condição de pesquisa de uma instrução SELECT, DELETE ou UPDATE.
A função RID retorna o RID de uma linha, que você pode usar para identificar exclusivamente uma linha.
Call the RID built-in function in the search condition of a SELECT, DELETE, or UPDATE statement.
The RID function returns the RID of a row, which you can use to uniquely identify a row.
Restrição: - Restriction:
Como o Db2 pode reutilizar números RID quando o utilitário REORG é executado, a função RID pode retornar valores diferentes quando chamada para uma linha várias
vezes.
Because Db2 might reuse RID numbers when the REORG utility is run, the RID function might return different values when invoked for a row multiple times.
Se você especificar um RID e o Db2 não puder localizar a linha por meio do acesso direto à linha, o Db2 não mudará para outro método de acesso. Em vez disso, Db2
não retorna nenhuma linha.
If you specify a RID and Db2 cannot locate the row through direct row access, Db2 does not switch to another access method. Instead, Db2 returns no rows.
© Copyright IBM Corp.
|