Using a From Clause in an Update Statement

So, lets say you have a table of data as follows:

And lets say you have a destination table with the same schema. But the data is not necessarily in the same order:
We’re told that the combination of first name and last name are unique in this schema. Now, the idea is to copy all of the primary keys in the top table to fill the nulls in the bottom table. Of course, this is easily done with a handful of update statements here. But what if both tables have thousands of rows? That’s where we can use SQL Server’s UPDATE statement with a FROM clause.

UPDATE ContactTableNew
SET id = cs.id
FROM ContactTableNew cn INNER JOIN ContactTableSource cs ON cs.fname = cn.fname and cs.lname = cn.lname

OK. So exactly what have we done? It’s kinda like a join. Well, it is a join. We have taken data from one table and updated the new table with that data.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>