If your version of SQL Server is higher than 2008, you have access to the MERGE
clause.
When you want to keep information synchronized between two tables (and 2 databases), it is excellent. With it, you hit a source and destination , and instruct what the bank should do for each line that exists in source . Example:
- If it exists at the source and destination, it updates the target
- If it does not exist in the destination, it inserts the registry
- If it does not exist in the source, remove it from the target table (probably the record was removed at the source).
Example of how it would look:
MERGE bancoDadosCliente..tb_cliente as target
USING (SELECT cd_cliente, ds_endereco FROM bancoDadosOrigem..tb_cliente) AS source
ON (target.cd_cliente = source.cd_cliente)
WHEN MATCHED THEN
UPDATE SET ds_endereco = source.ds_endereco
WHEN NOT MATCHED BY TARGET THEN
THEN DELETE
WHEN NOT MATCHED BY SOURCE THEN
INSERT (cd_cliente, ds_endereco)
VALUES (source.cd_cliente, source.ds_endereco)
See References: link
EDITION
If you want simpler commands, you can use simple INSERT
s and UPDATE
s, but you will have to make a tighter control on it. Examples:
To update records that in another bank that already have a cd_cliente
registered
UPDATE d
SET
d = ds_endereco -- aqui voce coloca uma lista das colunas a atualizar
FROM dbDestino..cd_cliente d
INNER JOIN dbOrigem..cd_cliente c
WHERE d.cd_cliente = c.cd_cliente
To insert the records that do not exist in the destination:
INERT INTO dbDestino..cd_cliente (cd_cliente, ds_endereco)
SELECT c.cd_cliente, c.ds_endereco
FROM dbDestino..cd_cliente d
OUTER JOIN dbOrigem..cd_cliente c ON d.cd_cliente = c.cd_cliente
WHERE d.cd_cliente IS NULL -- pega registros que não existem no destino e insere
Delete records that should not exist (have been deleted at the source:
DELETE FROM dbDestino..cd_cliente
WHERE cd_client NOT IN (
SELECT cd_cliente from dbOrigem..cd_cliente)