Update two tables with condition

Asked

Viewed 247 times

3

I have the following scenario Two Tables Source Table - Destination Table

Both with the same fields [ID] [name] [CPF]

The query must go in the [CPF] columns of the two tables, when the [CPF] of the Origin and Destination is equal, it must update the [Name] field of the Destination Table according to the Origin.

  • Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).

2 answers

8

Although you haven’t specified the SGBD, to query to the SQL Server, for example, it would look like this:

UPDATE dest
   SET dest.nome = ori.nome
  FROM destino dest
       INNER JOIN origem ori ON ori.cpf = dest.cpf

Some examples of the use of INNER JOIN are available in the article Microsoft Technet: Using internal junctions

2

For DBMS Oracle:

    UPDATE destino dest
       SET dest.nome = NVL((SELECT ori.nome
                              FROM origem ori
                             WHERE ori.cpf = dest.cpf), dest.nome);
  • 1

    The problem with its solution is that if there is no one at the origin with the same CPF, the field will be updated with null

  • 1

    I updated my code, added an NVL, predicting the null return of SELECT.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.