You did not specify how the result should be shown so I am proposing two options:
Using these records as an example:
create table contatonovo
(
codigo varchar(5) null
,nome varchar(50) null
,celular varchar(10) null
)
GO
create table contato
(
codigo varchar(5) null
,nome varchar(50) null
,celular varchar(10) null
)
GO
insert into contato values
('01','primeiro da silva', '1111-1111')
,('02','segundo contato', '2222-2222')
,('03','terceiro fulano', '3333-3333')
,('04','quarto sicrano', '4444-4444')
,('05','tudo igual', '5555-5555')
insert into contatonovo values
('01','primeiro da silva', null)
,('02','segundo contato da silva', '2222-2222')
,('03','terceiro fulano', '3003-3333')
,('04','quartos sicrano', null)
,('05','tudo igual', '5555-5555')
GO
You can show all records that have differences by showing each record once using a UNION
:
select nv.codigo, nv.nome as [Novo nome], at.nome as [Antigo nome], nv.celular as [Novo Celular], at.celular as [Antigo Celular]
from contatonovo nv
join contato at on at.codigo = nv.codigo
where coalesce(nv.nome,'') != coalesce(at.nome,'')
UNION
select nv.codigo, nv.nome as [Novo nome], at.nome as [Antigo nome], nv.celular as [Novo Celular], at.celular as [Antigo Celular]
from contatonovo nv
join contato at on at.codigo = nv.codigo
where coalesce(nv.celular,'') != coalesce(at.celular,'')
or showing a difference by record in this way by pointing out which field is different, again using UNION
p/ merge everything into a single dataset:
select nv.codigo, nv.nome as [Novo valor], at.nome as [Antigo valor], 'Nome' as [Diferença]
from contatonovo nv
join contato at on at.codigo = nv.codigo
where coalesce(nv.nome,'') != coalesce(at.nome,'')
UNION
select nv.codigo, nv.celular, at.celular, 'Celular'
from contatonovo nv
join contato at on at.codigo = nv.codigo
where coalesce(nv.celular,'') != coalesce(at.celular,'')
For the given example the results would be:
codigo Novo nome Antigo nome Novo Celular Antigo Celular
------ ------------------------ ------------------ ------------ --------------
01 primeiro da silva primeiro da silva NULL 1111-1111
02 segundo contato da silva segundo contato 2222-2222 2222-2222
03 terceiro fulano terceiro fulano 3003-3333 3333-3333
04 quartos sicrano quarto sicrano NULL 4444-4444
or
codigo Novo valor Antigo valor Diferença
------ ------------------------- ---------------- ---------
01 NULL 1111-1111 Celular
02 segundo contato da silva segundo contato Nome
03 3003-3333 3333-3333 Celular
04 NULL 4444-4444 Celular
04 quartos sicrano quarto sicrano Nome
Note: If you have the Visual Studio it comes with a reasonable database comparison tool capable of comparing Schema or Data.
Andrea, you’re going through relationship between
nv.codigo = atual.codigo
but they are not included in theSELECT
. Try to insert.– Maria Clara