En SQL Server, es posible insertar
en una tabla utilizando una sentencia SELECT
:
INSERT INTO Table (col1, col2, col3)
SELECT col1, col2, col3
FROM other_table
WHERE sql = 'cool'
¿Es posible también actualizar mediante una SELECT
? Tengo una tabla temporal que contiene los valores y me gustaría actualizar otra tabla utilizando esos valores. Tal vez algo como esto:
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'
Yo modificaría la excelente respuesta de Robin por lo siguiente:
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
)
Sin una cláusula WHERE, afectará incluso a filas que no necesitan ser afectadas, lo que podría (posiblemente) causar un recálculo del índice o disparar triggers que realmente no deberían haberse disparado.