I recently posted this on my personal
blog, however it's quite a useful tip so I thought I'd post it here too. Sometimes you may want to perform a mass update on a table based on the
contents of another table. The first thing you may think of is using a
cursor to scroll through Table A and update Table B line by line. This
is extremely slow. However, there is another way.
The way to do it is to join the two tables together then perform a self-update. I'll called the first table "Product" and the second table "UpdatedProduct".
UPDATE Product
SET Price = NewPrice
FROM Product
INNER JOIN UpdatedProduct ON UpdatedProduct.ProductId = Product.ProductId
So
what have I done there? Well the first two lines instruct the dbms to
update the Product table, altering the price. The second two lines
provide a join of the 2 tables we are using and an interim relation
that the Update can use as it's source. A table of 250,000 records
took 3 seconds to update with this method but over 30 minutes using a
cursor so the benefits are huge.
Currently rated 3.5 by 2 people
- Currently 3.5/5 Stars.
- 1
- 2
- 3
- 4
- 5