In SQL Server ist es möglich, eine Tabelle mit einer "SELECT"-Anweisung einzufügen:
INSERT INTO Table (col1, col2, col3)
SELECT col1, col2, col3
FROM other_table
WHERE sql = 'cool'
Ist es auch möglich, über eine SELECT-Anweisung eine Tabelle zu aktualisieren? Ich habe eine temporäre Tabelle, die die Werte enthält, und möchte eine andere Tabelle mit diesen Werten aktualisieren. Vielleicht so etwas wie dies:
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'
Ich würde Robins ausgezeichnete Antwort wie folgt abändern:
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
)
Ohne eine WHERE-Klausel werden auch Zeilen betroffen, die nicht betroffen sein müssen, was (möglicherweise) zu einer Neuberechnung des Index führen oder Trigger auslösen könnte, die eigentlich nicht hätten ausgelöst werden sollen.
Ein Weg
UPDATE t
SET t.col1 = o.col1,
t.col2 = o.col2
FROM
other_table o
JOIN
t ON t.id = o.id
WHERE
o.sql = 'cool'