SQL update from one Table to another based on a ID match SQL update from one Table to another based on a ID match sql-server sql-server

SQL update from one Table to another based on a ID match


I believe an UPDATE FROM with a JOIN will help:

MS SQL

UPDATE    Sales_ImportSET    Sales_Import.AccountNumber = RAN.AccountNumberFROM    Sales_Import SIINNER JOIN    RetrieveAccountNumber RANON     SI.LeadID = RAN.LeadID;

MySQL and MariaDB

UPDATE    Sales_Import SI,    RetrieveAccountNumber RANSET    SI.AccountNumber = RAN.AccountNumberWHERE    SI.LeadID = RAN.LeadID;


The simple Way to copy the content from one table to other is as follow:

UPDATE table2 SET table2.col1 = table1.col1, table2.col2 = table1.col2,...FROM table1, table2 WHERE table1.memberid = table2.memberid

You can also add the condition to get the particular data copied.


For SQL Server 2008 + Using MERGE rather than the proprietary UPDATE ... FROM syntax has some appeal.

As well as being standard SQL and thus more portable it also will raise an error in the event of there being multiple joined rows on the source side (and thus multiple possible different values to use in the update) rather than having the final result be undeterministic.

MERGE INTO Sales_Import   USING RetrieveAccountNumber      ON Sales_Import.LeadID = RetrieveAccountNumber.LeadIDWHEN MATCHED THEN   UPDATE       SET AccountNumber = RetrieveAccountNumber.AccountNumber;

Unfortunately the choice of which to use may not come down purely to preferred style however. The implementation of MERGE in SQL Server has been afflicted with various bugs. Aaron Bertrand has compiled a list of the reported ones here.