Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bulk Record Update with SQL

I have two tables in a SQL Server 2008 environment with the following structure

Table1 - ID - DescriptionID - Description  Table2 - ID - Description 

Table1.DescriptionID maps to Table2.ID. However, I do not need it any more. I would like to do a bulk update to set the Description property of Table1 to the value associated with it in Table2. In other words I want to do something like this:

UPDATE   [Table1]  SET   [Description]=(SELECT [Description] FROM [Table2] t2 WHERE t2.[ID]=Table1.DescriptionID) 

However, I'm not sure if this is the appropriate approach. Can someone show me how to do this?

like image 718
user208662 Avatar asked Jul 08 '11 18:07

user208662


People also ask

How can I update 1 million records in SQL Server?

One of my favorite ways of dealing with millions of records in a table is processing inserts, deletes, or updates in batches. Updating data in batches of 10,000 records at a time and using a transaction is a simple and efficient way of performing updates on millions of records.


2 Answers

Your way is correct, and here is another way you can do it:

update      Table1 set         Description = t2.Description from        Table1 t1 inner join  Table2 t2 on          t1.DescriptionID = t2.ID 

The nested select is the long way of just doing a join.

like image 110
Tocco Avatar answered Oct 06 '22 21:10

Tocco


Your approach is OK

Maybe slightly clearer (to me anyway!)

UPDATE   T1 SET   [Description] = t2.[Description] FROM    Table1 T1    JOIN    [Table2] t2 ON t2.[ID] = t1.DescriptionID 

Both this and your query should run the same performance wise because it is the same query, just laid out differently.

like image 38
gbn Avatar answered Oct 06 '22 20:10

gbn