0

I've never asked a question here before, and I'm not very advanced with sql whatsoever beyond simple queries so I apologize if I sound inept, very different from the programming I am used to. But today I am stuck in a unique position trying to solve a problem with no assistance, so I am hoping to get some ideas on here or knowledge.

I have Table A and Table B. They have various different columns except for the two they have in common, ID and phone number. Sometimes, a few rows in Table B will have NULL in the phone number. I need to write something that will select all records from Table A by ID and phone number, look up the same IDs in Table B, and if B's phone number field is NULL it will update it with the phone number from A.

I really hope this makes sense. I had begun writing a loop to try to accomplish this by iteration as I might with my other programming but everywhere I read said SQL was not made to do loops so stay away. I appreciate any input.

Taylor

2 Answers2

0

I would check this out: Updating denormalized database tables

You could eliminate this problem by "normalizing" the tables and getting rid of redundant sets of data. However, denormalized data can be more efficient than normalized data in certain situations.

Anthony C
  • 71
  • 3
0

First get the results you want by creating a Select statement.

Select A.ID as AID, B.ID as BID, A.Phone as APhone, B.Phone as BPhone
From TableA A
JOIN TableB B on A.ID = B.ID
Where B.Phone is Null

Then you can form this into your Update statement very easily.

Update B
Set Phone = A.Phone
From TableA A
    JOIN TableB B on A.ID = B.ID
    Where B.Phone is Null
SS_DBA
  • 2,403
  • 1
  • 11
  • 15
  • this should work for you @TaylorMeow, in addition you can add isnull function if B.Phone is sometimes empty, other time NULL. where isnull(B.Phone, '') = '' – Pawel Czapski Jul 19 '17 at 14:57
  • 1
    OMG! That works! I'm still forming the update part but my results were exactly the records I needed with the right fields! Ah I'm so relieved my day might not be so bad afterall. I cannot thank you all enough for the help. I think this where I make my comment there were a lot of places to add one... But yes this is resolved I'm happy as a clam. – TaylorMeow Jul 19 '17 at 15:12
  • Glad this worked for you @TaylorMeow. Please accept this as your answer. Thank you! – SS_DBA Jul 19 '17 at 15:25