I have two tables in different databases with the same structure, in database1 the information arrives at one of the tables, the information that arrives at this table I have to pass to the table of database2 .
I have the following script that does this without any problem, no matter how many times I execute it, it does not enter duplicates, it only enters the records that are in database1 and that are not in database2
INSERT INTO [Datos1].dbo.lotesInsert (Codlote,Animal,Peso)
SELECT *
FROM [Datos2].dbo.lotesInsert T1
WHERE NOT EXISTS (SELECT NULL
FROM [Datos1].dbo.lotesInsert T2
WHERE t2.Codlote = t1.Animal)
This is how the data stays when I run the script, it sends them to the other database without problem, if I insert another animal in database1, that is, the next one, it only sends that one, it does not duplicate the data, it only sends those that do not exist in the database2 " This
is how the information arrives in database2"
But when I change the batch it duplicates the previous batch, in the image we see that if there is a batch it inserts it fine without duplicates without problem, but I insert batch 18101 it duplicates batch 18100
"This is how it is in the database1"
here I already run the script with the data of the new batch, the new batch inserts it well, but it duplicates the previous
one "so they reach the database2"
I have a solution for this or an explanation of why it happens and thus solve it
From what I basically understand, you have the detail in the
SELECT
(which is finally the one that "decides" which elements will be taken to pass to theINSERT
; now I'll tell you, since you want it not to be repeatedCodLote
andAnimal
I suggest the following Query (focusing on itSELECT
for place it where you already have it):If you need to, do not include it, and if it matches , add the separator and the Weight
Peso
field to both CONCATs in the parts of T1 and T2.