SQL serverī ir iespējams ievietot
tabulā, izmantojot SELECT
izteikumu:
INSERT INTO Table (col1, col2, col3)
SELECT col1, col2, col3
FROM other_table
WHERE sql = 'cool'
Vai ir iespējams arī atjaunināt, izmantojot SELECT
? Man ir pagaidu tabula, kurā ir vērtības, un es gribētu atjaunināt citu tabulu, izmantojot šīs vērtības. Iespējams, kaut kas līdzīgs šādam:
UPDATE Table SET col1, col2
SELECT col1, col2
FROM other_table
WHERE sql = 'cool'
WHERE Table.id = other_table.id
UPDATE
Table_A
SET
Table_A.col1 = Table_B.col1,
Table_A.col2 = Table_B.col2
FROM
Some_Table AS Table_A
INNER JOIN Other_Table AS Table_B
ON Table_A.id = Table_B.id
WHERE
Table_A.col3 = 'cool'
Es izmainītu Robin's lielisko atbildi uz šādu:
UPDATE Table
SET Table.col1 = other_table.col1,
Table.col2 = other_table.col2
FROM
Table
INNER JOIN other_table ON Table.id = other_table.id
WHERE
Table.col1 != other_table.col1
OR Table.col2 != other_table.col2
OR (
other_table.col1 IS NOT NULL
AND Table.col1 IS NULL
)
OR (
other_table.col2 IS NOT NULL
AND Table.col2 IS NULL
)
Bez WHERE klauzulas jūs ietekmēsiet pat tās rindas, kuras nav jāietekmē, kas (iespējams) var izraisīt indeksu pārrēķinu vai iedarbināt trigerus, kurus tiešām nevajadzēja iedarbināt.