Saturday, January 26, 2008

Bulk Updates in T-SQL without Cursors

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.

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. At 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.

2 comments:

Johnny Methane said...

This is great! Just what I was looking for, thanks very much.

søren said...

Thanx... :-)
Just what I needed.