I SQL Server er det muligt at indsætte
i en tabel ved hjælp af en SELECT
-anvisning:
INSERT INTO Table (col1, col2, col3)
SELECT col1, col2, col3
FROM other_table
WHERE sql = 'cool'
Er det også muligt at opdatere via en SELECT
? Jeg har en midlertidig tabel med værdierne og vil gerne opdatere en anden tabel ved hjælp af disse værdier. Måske noget i stil med dette:
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'
Jeg ville ændre Robin's fremragende svar til følgende:
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
)
Uden en WHERE-klausul påvirker du selv rækker, der ikke behøver at blive påvirket, hvilket (muligvis) kan forårsage indeksgennemregning eller udløse triggere, der egentlig ikke burde være udløst.