Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Update table only if field is null

Author  Topic 

Goalie35
Yak Posting Veteran

81 Posts

Posted - 2011-08-25 : 15:57:35
I have 2 tables (TableA and TableB). Both have the same field names but if certain fields in TableA are null, I need to populate that field with the value from TableB

So for example:
Table A:
ID | Name | Address
-----------------------
1 | John Smith | 123 Any St.
2 | Amy Andrews | <null>

Table B:
ID | TableA_ID | Name | Address
-------------------------------------------
13 | 1 | John Smith | 123 Any St.
18 | 56 | Peter Robbins | 18 Strathmore Ln.
22 | 2 | Amy Andrews | 456 Park Ave.

After running my update, my TableA should look as follows:
TableA:
ID | Name | Address
-----------------------
1 | John Smith | 123 Any St.
2 | Amy Andrews | 456 Park Ave.

What's the best way to make these updates to the null TableA fields?
Thanks.

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-08-25 : 16:04:20
UPDATE a
SET Address = b.Address
FROM TableA a
JOIN TableB b
ON a.ID = b.TableA_ID
WHERE a.Address IS NULL

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

Goalie35
Yak Posting Veteran

81 Posts

Posted - 2011-08-30 : 09:35:31
That worked, thanks!
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-08-30 : 10:45:51
You're welcome, glad to help.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -