/ / Istruzione di aggiornamento TSQL Esecuzione - sql-server, tsql, sql-update

Istruzione di aggiornamento TSQL Esecuzione - sql-server, tsql, sql-update

inserisci la descrizione dell'immagine qui

Ho una tabella con campi definiti dall'utente che voglio mantenere aggiornati in base alla tabella. Per fare ho creato la seguente query

select
a + b + c + d + e + f + g + h
from
(select
"update gl00100 set USERDEF1 =" as a,
"""" + DMA + """" as b,
", set USERDEF2 =" as c,
"""" + Brand + """" as d,
", set USRDEFS1 =" as e,
"""" + convert(char(10), dateopened, 120) + """" as f,
"where actnumbr_2 =" as g,
GPStore as h
from
[192.168.xxx.xx].bi.dbo.store
where
store <> 0000 and DateOpened is not null) x

Come puoi dire, la query sta creando le istruzioni di aggiornamento che voglio eseguire. Come posso eseguire la query e quindi eseguire i risultati. È possibile?

risposte:

1 per risposta № 1

Prova questo:

DECLARE @sql nvarchar(2000)
DECLARE #crs INSENSITIVE CURSOR FOR
SELECT "update gl00100 set USERDEF1 =" as a, """"+DMA+"""" as b, ",
set USERDEF2 =" as c, """"+Brand+"""" as d, ", set USRDEFS1 =" as e,
""""+convert(char(10),dateopened,120)+"""" as f, "where actnumbr_2 =" as g,
GPStore as h
from [192.168.xxx.xx].bi.dbo.store where store <> 0000 and DateOpened is not null
OPEN #crs
FETCH NEXT FROM #crs INTO @sql
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC sp_executesql @sql
FETCH NEXT FROM #crs INTO @sql
END
CLOSE #crs
DEALLOCATE #crs

0 per risposta № 2

Puoi farlo usando a JOIN piuttosto che costruire istruzioni SQL dinamiche ed eseguirle una ad una:

UPDATE  g
SET     USERDEF1 = s.DMA,
USERDEF2 = s.Brand,
USRDEFS1 = s.DateOpened
FROM    gl00100 AS g
INNER JOIN [192.168.xxx.xx].bi.dbo.store AS s
ON s.GPStore = g.actnumbr_2
WHERE   s.Store <> 0000
AND     s.DateOpened IS NOT NULL;

Potresti anche scoprire che ottieni prestazioni migliori usando OPENQUERY, quando si utilizzano 4 nomi di parte per un server incrociatoquery, non puoi trarre vantaggio dalle statistiche, quindi potresti finire per trascinare l'intero store table in memoria, solo per selezionare alcune righe alla fine, quindi potresti provare qualcosa del genere:

UPDATE  g
SET     USERDEF1 = s.DMA,
USERDEF2 = s.Brand,
USRDEFS1 = s.DateOpened
FROM    gl00100 AS g
INNER JOIN OPENQUERY
(   [192.168.xxx.xx],
"SELECT DMA, Brand, DateOpened, GPStore
FROM bi.dbo.store
WHERE store <> 0000 AND DateOpened is not null"
) AS s
ON s.GPStore = g.actnumbr_2