Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I UPDATE from a SELECT in SQL Server?

In SQL Server, it is possible to insert rows into a table with an INSERT.. SELECT statement:

INSERT INTO Table (col1, col2, col3) SELECT col1, col2, col3  FROM other_table  WHERE sql = 'cool' 

Is it also possible to update a table with SELECT? I have a temporary table containing the values and would like to update another table using those values. Perhaps something like this:

UPDATE Table SET col1, col2 SELECT col1, col2  FROM other_table  WHERE sql = 'cool' WHERE Table.id = other_table.id 
like image 795
jamesmhaley Avatar asked Feb 25 '10 14:02

jamesmhaley


People also ask

Can we do an update from a SELECT statement?

The UPDATE from SELECT query structure is the main technique for performing these updates. An UPDATE query is used to change an existing row or rows in the database. UPDATE queries can change all tables' rows, or we can limit the update statement affects for certain rows with the help of the WHERE clause.

How do I use update SELECT?

The SELECT FOR UPDATE statement is used to order transactions by controlling concurrent access to one or more rows of a table. It works by locking the rows returned by a selection query, such that other transactions trying to access those rows are forced to wait for the transaction that locked the rows to finish.

How do you update a specific record in SQL?

First, specify the table name that you want to change data in the UPDATE clause. Second, assign a new value for the column that you want to update. In case you want to update data in multiple columns, each column = value pair is separated by a comma (,). Third, specify which rows you want to update in the WHERE clause.

Is there a way to SELECT and update rows at the same time?

in SQL 2008 a new TSQL statement "MERGE" is introduced which performs insert, update, or delete operations on a target table based on the results of a join with a source table. You can synchronize two tables by inserting, updating, or deleting rows in one table based on differences found in the other table.


1 Answers

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' 
like image 178
Robin Day Avatar answered Sep 29 '22 23:09

Robin Day