Sunday, July 29, 2012

SQL Updating One Table from Another Table

Recently, I had to do a dataconversion (field needed float - long story) but the table stored nvarchars. And SQL Studio wouldn't let me do a direct conversion in the designer. So, I made a backup table, then nulled out the offending field, changed the datatype, then had to bring back the correct data.

I've done this before, but I never remember the syntax, so here it is.

I often forget how to do this in T-SQL, so as an opener for this blog, here it is.

 UPDATE  Tech
SET  Tech.Zipcode = s.ZipCode
FROM  Tech t
INNER JOIN   SafeBackupTech s
ON   t.UserName = s.UserName

Also, you can do it this way:

UPDATE Tech 
SET ZipCode = SafeBackupTech.ZipCode
FROM Tech, SafeBackupTech 
WHERE Tech.UserName = SafeBackupTech.UserName

Thanks to StackOverflow for the answers to this and many other brain-fart related questions.
(http://stackoverflow.com/questions/224732/sql-update-from-one-table-to-another-based-on-a-id-match)

No comments:

Post a Comment