Em **SQL Server***, é possível inserir
em uma tabela utilizando uma instrução SELECT
:
INSERT INTO Table (col1, col2, col3)
SELECT col1, col2, col3
FROM other_table
WHERE sql = 'cool'
Também é possível actualizar através de um SELECT
? Eu tenho uma tabela temporária contendo os valores e gostaria de atualizar outra tabela utilizando esses valores. Talvez algo parecido com isto:
UPDATE Table SET col1, col2
SELECT col1, col2
FROM other_table
WHERE sql = 'cool'
WHERE Table.id = other_table.id
Eu modificaria a excelente resposta de Robin para o seguinte:
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
)
Sem uma cláusula WHERE, você afetará até mesmo as linhas que não precisam ser afetadas, o que poderia (possivelmente) causar recálculo de índice ou gatilhos de incêndio que realmente não deveriam ter sido disparados.