DB2 12 - Selecting values while merging data


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 12 - Seleção de valores ao mesclar dados - Selecting values while merging data

Ao atualizar os dados existentes e inserir novos dados em uma única operação de mesclagem, você pode selecionar valores dessas linhas ao mesmo tempo.
When you update existing data and insert new data in a single merge operation, you can select values from those rows at the same time.

Sobre esta tarefa - About this task

Você pode selecionar valores de linhas que estão sendo mescladas, especificando a instrução MERGE na cláusula FROM da instrução SELECT.
Ao mesclar uma ou mais linhas em uma tabela, você pode recuperar:
You can select values from rows that are being merged by specifying the MERGE statement in the FROM clause of the SELECT statement.
When you merge one or more rows into a table, you can retrieve:

  • O valor de uma coluna gerada automaticamente, como um ROWID ou coluna de identidade
    The value of an automatically generated column such as a ROWID or identity column

  • Quaisquer valores padrão para colunas
    Any default values for columns

  • Todos os valores para uma linha mesclada, sem especificar nomes de coluna individuais
    All values for a merged row, without specifying individual column names

  • Valores calculados com base nas alterações nas linhas mescladas
    Calculated values based on the changes to merged rows

Especifique a cláusula FINAL TABLE com instruções SELECT FROM MERGE.
A TABELA FINAL consiste nas linhas da tabela ou visão após a fusão ocorrer.
Specify the FINAL TABLE clause with SELECT FROM MERGE statements.
The FINAL TABLE consists of the rows of the table or view after the merge occurs.

Exemplo: - Example:

Suponha que você precise inserir dados na tabela STOCK, que contém os símbolos das ações da empresa e os preços das ações de seu portfólio de ações.
Alguns de seus dados de entrada referem-se a empresas que já estão na tabela STOCK; alguns dos dados referem-se a empresas que você está adicionando à sua carteira de ações.
Se o símbolo de ação existir na coluna SÍMBOLO da tabela ESTOQUE, será necessário atualizar a coluna PREÇO.
Se o símbolo das ações da empresa ainda não estiver na tabela STOCK, você precisará inserir uma nova linha com o símbolo das ações e o preço das ações.
Além disso, você precisa adicionar um novo valor DELTA à sua saída para mostrar a mudança no preço das ações.

Suppose that you need to input data into the STOCK table, which contains company stock symbols and stock prices from your stock portfolio.
Some of your input data refers to companies that are already in the STOCK table; some of the data refers to companies that you are adding to your stock portfolio.
If the stock symbol exists in the SYMBOL column of the STOCK table, you need to update the PRICE column.
If the company stock symbol is not yet in the STOCK table, you need to insert a new row with the stock symbol and the stock price.
Furthermore, you need to add a new value DELTA to your output to show the change in stock price.

Suponha que a tabela STOCK contenha os dados mostrados na Tabela 1.
Suppose that the STOCK table contains the data that is shown in Table 1.

Tabela 1. Tabela STOCK antes da instrução SELECT FROM MERGE - Table 1. STOCK table before SELECT FROM MERGE statement

SYMBOL PRICE
XCOM 95.00
YCOM 24.50

Agora, suponha que: hv_symbol e: hv_price sejam matrizes de variáveis ??de host que contêm dados atualizados que correspondem aos dados mostrados na Tabela 1.
A Tabela 2 mostra os dados de variáveis ??de host para atividade de estoque.
Now, suppose that :hv_symbol and :hv_price are host variable arrays that contain updated data that corresponds to the data that is shown in Table 1.
Table 2 shows the host variable data for stock activity.

Tabela 2. Matrizes de variáveis ??de host de atividade de estoque - Table 2. Host variable arrays of stock activity

hv_symbol hv_price
XCOM 97.00
NEWC 30.00
XCOM 107.00

NEWC é novo na tabela STOCK, portanto, seu símbolo e preço precisam ser inseridos na tabela STOCK.
As linhas para XCOM na Tabela 2 representam os preços das ações alterados, portanto, esses valores precisam ser atualizados na tabela STOCK.
Além disso, a saída precisa mostrar a mudança nos preços das ações como um valor DELTA.

NEWC is new to the STOCK table, so its symbol and price need to be inserted into the STOCK table.
The rows for XCOM in Table 2 represent changed stock prices, so these values need to be updated in the STOCK table.
Also, the output needs to show the change in stock prices as a DELTA value.

A seguinte instrução SELECT FROM MERGE atualiza o preço de XCOM, insere o símbolo e o preço de NEWC e retorna uma saída que inclui um valor DELTA para a alteração no preço das ações.
The following SELECT FROM MERGE statement updates the price of XCOM, inserts the symbol and price for NEWC, and returns an output that includes a DELTA value for the change in stock price.

SELECT SYMBOL, PRICE, DELTA FROM FINAL TABLE
  (MERGE INTO STOCK AS S INCLUDE (DELTA DECIMAL(5,20)
   USING ((:hv_symbol, :hv_price) FOR :hv_nrows ROWS) AS R (SYMBOL, PRICE)
   ON S.SYMBOL = R.SYMBOL
     WHEN MATCHED THEN UPDATE SET 
       DELTA = R.PRICE - S.PRICE, PRICE=R.PRICE
     WHEN NOT MATCHED THEN INSERT 
       (SYMBOL, PRICE, DELTA) VALUES (R.SYMBOL, R.PRICE, R.PRICE)  
NOT ATOMIC CONTINUE ON SQLEXCEPTION);

A cláusula INCLUDE especifica que uma coluna adicional, DELTA, pode ser retornada na saída sem adicionar uma coluna à tabela STOCK.
A parte UPDATE da instrução MERGE define o valor DELTA para o diferencial do preço da ação anterior com o valor definido para a operação de atualização.
A parte INSERT da instrução MERGE define o valor DELTA com o mesmo valor da coluna PRICE.

The INCLUDE clause specifies that an additional column, DELTA, can be returned in the output without adding a column to the STOCK table.
The UPDATE portion of the MERGE statement sets the DELTA value to the differential of the previous stock price with the value set for the update operation.
The INSERT portion of the MERGE statement sets the DELTA value to the same value as the PRICE column.

Depois que a instrução SELECT FROM MERGE é processada, a tabela STOCK contém os dados que são mostrados na Tabela 3.
After the SELECT FROM MERGE statement is processed, the STOCK table contains the data that is shown in Table 3.

Tabela 3. Tabela STOCK após a instrução SELECT FROM MERGE - Table 3. STOCK table after SELECT FROM MERGE statement

SYMBOL PRICE
XCOM 107.00
YCOM 24.50
NEWC 30.00

A seguinte saída da instrução SELECT FROM MERGE inclui atualizações para XCOM e um valor DELTA para cada linha de saída.
The following output of the SELECT FROM MERGE statement includes both updates to XCOM and a DELTA value for each output row.

   SYMBOL    PRICE      DELTA
   =============================
   XCOM       97.00      2.00
   NEWC       30.00     30.00
   XCOM      107.00     10.00

Parent topic: Inserting data and updating data in a single operation



© Copyright IBM Corp.