-1

I have a problem in SQL Server. I have a query

select FirstName, + ", " + LastName as FullName

If LastName = NULL and FirstName = "Fred"

Then FullName would be NULL. Is there a way to just have the FirstName instead?

Here is what I get: https://i.stack.imgur.com/NbLWL.png

Dale K
  • 25,246
  • 15
  • 42
  • 71
Samuel
  • 3
  • 1
  • As per the question guide, please DO NOT post images of code, data, error messages, etc. - copy or type the text into the question. Please reserve the use of images for diagrams or demonstrating rendering bugs, things that are impossible to describe accurately via text. – Dale K Apr 22 '21 at 01:28

3 Answers3

2

Since SQL Server 2017, you can use concat_ws():

select concat_ws(', ', firstname, lastname)

In earlier versions, you can use:

select stuff( concat(', ' + firstname,
                     ', ' + lastname
                    ), 1, 2, ''
            )
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
2

I would go with

Select Case 
    When LastName Is Null 
    Then FirstName 
    Else Concat(FirstName, ", ", LastName) 
End As FullName
Nicholas Hunter
  • 1,791
  • 1
  • 11
  • 14
0

In addition to concat function, if you are having very old sql server version, you can use ISNULL to fill up empty string in place of null value.

select 
CASE WHEN LastName IS NOT NULL 
     THEN ISNULL(FirstName,'') + ", " + LastName
     ELSE ISNULL(FirstName,'') END as FullName
Venkataraman R
  • 12,181
  • 2
  • 31
  • 58