Search code examples
sql-serverperformancequery-performance

Optimizing a Sql Server Query to update large list


I have to update the Articles in a table (Table to be updated: Articolo), with items in another table (Table with new articles: TabellaTemp), now the problem is that I have to update the old articles in more I have to insert the new ones ! To do so I use the queries below, the first updates the existing articles, the second one inserts the new ones, the second query is really very slow takes almost 20 minutes to insert the new articles (The articles are more than 500 thousand)! Is there a way to improve the performance of this query on Sql Server?

I entered the structure of the tables here: http://www.sqlfiddle.com/#!6/4f4ea

QUERY 1:

Update Articolo set Articolo.Stato = 'Disponibile',Articolo.Prezzo = TabellaTemp.PRZNETTO,Articolo.PrezzoListino = TabellaTemp.PRZCASA,Articolo.DataAggiornamento = TabellaTemp.DATAAGG,Articolo.Descrizione = TabellaTemp.DESCR,Articolo.UM = TabellaTemp.UM
from Articolo
inner join TabellaTemp
on TabellaTemp.CodMarca = Articolo.CodMarca and TabellaTemp.CODART = Articolo.CodArt 
where Articolo.Importato = 'COMET'

Query 2:

Insert into Articolo(CodMarca, CodArt, Descrizione, UM, Prezzo, PrezzoListino, DataAggiornamento, Fornitore, Importato) 
SELECT CODMARCA, CODART, DESCR, UM, PRZNETTO, PRZCASA, DATAAGG,'COMET' as Fornitore,'COMET' as Importato 
FROM TabellaTemp as T 
where CODART not in (select CodArt from Articolo where Importato = 'COMET') and CODMARCA  not in (select CodArt from Articolo where Importato = 'COMET')

Solution

  • Replacing the IN Statement with exists can bring a large performance improvement

    Insert into Articolo(CodMarca, CodArt, Descrizione, UM, Prezzo, PrezzoListino, DataAggiornamento, Fornitore, Importato) 
    SELECT 
        CODMARCA, 
        CODART, 
        DESCR, 
        UM, 
        PRZNETTO, 
        PRZCASA, 
        DATAAGG,
        'COMET' as Fornitore,
        'COMET' as Importato 
        FROM TabellaTemp as T 
            WHERE NOT EXISTS
            (
                select 1 from Articolo where Importato = 'COMET' AND (CodArt =T.CodArt OR CodArt = T.CODMARCA)
            )
    

    Also, try indexing the columns on the table TabellaTemp to improve the performance