Column join only if its value is not NULL

I have a SQL Server table as follows:

-------------------------------------------------------------------
PERSON
-------------------------------------------------------------------
   NAME   |   PHONE   |   PHONE1   |   PHONE2   |   PHONE_CONCAT  
-------------------------------------------------------------------
   Name1  |   12345   |   Null     |   Null     |   Null
   Name2  |   Null    |   54774    |   Null     |   Null
   Name3  |   Null    |   Null     |   77841    |   Null
-------------------------------------------------------------------

What I want to do is concatenate in PHONE_CONCAT the columns PHONE, PHONE1 and PHONE2 only when the value for one of these columns is! = Null. So, in this case, the final value for the PHONE_CONCAT column will be:

------------------
PERSON
------------------
   PHONE_CONCAT  
------------------
   12345
   54774
   77841
 ------------------

Could you help me complete this action?

I want to update the value of PHONE_CONCAT, so I will need to update for each row in the table.

+4
source share
2 answers

Is this what you want?

select coalesce(t.phone, t.phone1, t.phone2) as phone_concat
from t;

, NULL. .

+7

select:

SELECT COALESCE(t.phone,'') + COALESCE(t.phone1,'') + COALESCE(t.phone2,'') 
FROM PERSON t

:

UPDATE PERSON t
SET t.PHONE_CONCAT = COALESCE(t.phone,'') + COALESCE(t.phone1,'') + COALESCE(t.phone2,'') 
+5

Source: https://habr.com/ru/post/1659523/


All Articles