IMG-LOGO

How to update data from one table to another table in TSQL?

andy - 22 Dec, 2020 1293 Views 0 Comment

If you want to update from one table data to another table you can easily inner join the table by the same id key field and set the table the alias to perform the update.

Let's say we have two tables named Products and Products_Copy. Basically, both tables have the same field information. We want to copy the column fields value of Products_Copy to the Products table. In this example, we want to copy the Name and Price value.

Here is the screenshot of both table designs including the table values.

What we want to do is to update the products with ID: 1 and 2. So it will have the updated product name and price.
We can do it easily by running the following TSQL query.


UPDATE P
SET P.Name = PC.Name,
	P.Price = PC.Price
FROM dbo.Products P
INNER JOIN dbo.Products_Copy PC
ON P.Id = PC.Id

Here is the final result after we run the above TSQL query.

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

How to restore database using SQL query in TSQL?

If you have a database backup bak file extension and want to restore it using SQL query You can use the built in RESTORE DATABASE function Remember in order to be able to restore a database successfully You need to ...

How to get all table sizes in TSQL?

To get the information about how much space or size used by tables You can retrieve the size information by linking multiple tables in sys tables There are two tables that hold this information The first one is the sys ...