If your version of SQL Server is higher than 2008, you have access to the clause MERGE
.
When you want to keep information synchronized between two tables (and 2 databases), it is excellent. With it, you arrow one origin and fate, and instructed what the bank should do for each line in the origin. Example:
- If it exists at source and destination, refreshes the destination
- If it does not exist in the destination, enter the record
- If it does not exist at source, remove it from the target table (probably the record was removed at 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: http://msdn.microsoft.com/en-us/library/bb510625%28v=sql.100%29.aspx
EDITION
If you want simpler commands, you can use simple INSERT
s and UPDATE
s, but will have to make a stricter control on no. Examples:
To update records that in the other bank that already have one 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 enter 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
Deletes records that should not exist (deleted at source:
DELETE FROM dbDestino..cd_cliente
WHERE cd_client NOT IN (
SELECT cd_cliente from dbOrigem..cd_cliente)
I think I don’t quite understand your question yet. Please give the structure of the two databases. You want to keep the same cd_client on both sides?
– rodrigogq