0

I have a table in SQL Server hat has:

FirstName, LastName, MiddleName, CellNumber, HomeNumber
John Smith M 111-111-1111, 222-222-2222

The person can have both CellNumber and HomeNumber or can have CellNumber but no HomeNumber or can have HomeNumber and no CellNumber.

How do i write a query that will always return CellNumber if exists and HomeNumber only if CellNumber is NULL or blank.

SQL query to produce following results:

FirstName, LastName, MiddleName, NumberToUse, PhoneType
John Smith M 111-111-1111 CellNumber

Thanks for your help.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
Andy P.
  • 39
  • 9
  • Possible duplicate of [How do I check if a Sql server string is null or empty](https://stackoverflow.com/questions/334108/how-do-i-check-if-a-sql-server-string-is-null-or-empty) – stefancarlton Jan 25 '18 at 03:19

5 Answers5

0

You use case:

select . . .,
       (case when cellNumber is not null or cellNumber <> '' then cellNumber else homeNumber en) as NumberToUse,
       (case when cellNumber is not null  or cellNumber <> '' then 'Cell' else 'Home' end) as PhoneType
from t;

If blank could include spaces, you can remove the spaces (for the comparison) using replace() or ltrim().

The comparison to for is not null is, strictly speaking, not necessary. But it makes the query's intention more obvious.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Just one case when statement to first check if CellNumber is available, else fallback to HomeNumber.

SELECT 
    FirstName, 
    LastName, 
    MiddleName,
    CASE WHEN  
        CellNumber IS NOT NULL THEN CellNumber
    ELSE 
        HomeNumber 
    END AS NumberToUse,
    PhoneType
FROM
    TableName
Bae
  • 88
  • 6
0

coalesce is your friend here.. it returns the first non null values in the list.. so you don't have to do a whole heap of case statements

 select coalesce(cellnumber,HomeNumber) from yourtable
Harry
  • 2,636
  • 1
  • 17
  • 29
0

Another option is Coalesce() in concert with NullIf()

Example

Select FirstName 
      ,LastName
      ,MiddleName 
      ,DefaultPhone = coalesce(NullIf(CellNumber,'')+' Cell',NullIf(HomeNumber,'')+' Home')
 from YourTable
John Cappelletti
  • 79,615
  • 7
  • 44
  • 66
0
select FirstName, LastName, MiddleName,
case when isnull(CellNumber, '') = '' then HomeNumber else CellNumber end as NumberToUse,
case when isnull(CellNumber, '') = '' then 'HomeNumber' else 'CellNumber' end as PhoneType
from ...
Gordon Bell
  • 13,337
  • 3
  • 45
  • 64