Friday, December 7, 2007

Insert Data Into One Table If Criteria Matches Data in a Different Table

I know this sounds very simplistic, but you'd be surprised how many people simply have no clue how to do this:

You want to update Column1 in TableA to match Column1 in TableB as long as Column2 in TableA matches Column2 in TableB:

Here's how the query should look:

UPDATE TableA
SET Column1 = B.Column1
FROM TableA A
INNER JOIN TableB B
ON A.Column2 = B.Column2