Domanda

Ho i seguenti dati in una tabella TABLE1

DOCUMENTO ------ CAMPO1
12345
23456
34567
45678
98765

ho i seguenti dati in una vista VIEW1

DOCUMENTO ---- AUTOBUS
12345 ------------ 5
23456 ------------ 6
34567 ------------ 8
45678 ------------ 12
98765 ------------ 14

Quello che vorrei fare è aggiornare ogni riga

se (tabella1.document = vista1.document)
allora tabella1.campo1 = vista1.bus

Qualsiasi intuizione aiuterà.

Grazie.

È stato utile?

Soluzione

Ciò può essere fatto utilizzando SQL semplice, senza procedure richieste:

UPDATE table1 SET field1 = (SELECT bus FROM view1 WHERE table1.document = view1.document)

Oppure, se il tuo database lo consente:

UPDATE (select table1.field1, view1.bus FROM table1 JOIN view1 ON table1.document = view1.document) SET table1.field1 = view1.bus

Altri suggerimenti

Come ha detto Dan, ma in MS SQL Server trovo questo stile più facile da leggere:

UPDATE U
SET U.field1 = V.bus 
FROM table1 AS U
    JOIN view1 AS V
       ON V.document = U.document

Tieni presente che se VIEW1 può avere più righe per un dato valore [DOCUMENT] della riga TABLE1, il valore [BUS] scelto per aggiornare TABLE1 sarà casuale, all'interno del set corrispondente.(Se questo è il caso, la query potrebbe essere modificata per scegliere MAX / MIN / ecc.)

Perfetterei questa query per NON aggiornare alcuna riga che già corrisponde al valore BUS, il che la renderà più veloce se viene eseguita nuovamente e quindi alcuni valori esistono già in TABLE1

UPDATE U
SET U.field1 = V.bus 
FROM table1 AS U
    JOIN view1 AS V
       ON V.document = U.document
WHERE    U.field1 = V.bus
      OR (U.field1 IS NOT NULL AND V.bus IS NULL)
      OR (U.field1 IS NULL AND V.bus IS NOT NULL)

puoi tralasciare i test NULL / NOT NULL se il campo è definito in modo da non consentire NULL.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top