Dans SQL Server, il est possible d'effectuer une "insertion" dans une table à l'aide d'une instruction "SELECT" :
INSERT INTO Table (col1, col2, col3)
SELECT col1, col2, col3
FROM other_table
WHERE sql = 'cool'
Est-il également possible d'effectuer une mise à jour à l'aide d'une instruction SELECT
? J'ai une table temporaire contenant les valeurs et je voudrais mettre à jour une autre table en utilisant ces valeurs. Peut-être quelque chose comme ceci :
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'
Je modifierais l'excellente réponse de Robin comme suit :
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
)
Sans clause WHERE, vous affecterez même des lignes qui n'ont pas besoin d'être affectées, ce qui pourrait (éventuellement) entraîner un nouveau calcul de l'index ou déclencher des déclencheurs qui n'auraient pas dû être déclenchés.