Concatenate and Null value in Select

  • Simplest way is

    SELECT LastName + ', ' + FirstName+ ', ' + COALESCE(MiddleInit,'') AS Name

  • Thank you, sir!

  • --

    There is also a trick to handling spaces, commas, or other separators, which is shown in the examples below. The trick is to test an expression which includes the nullable column and the separator. If the column is null, then the expression will be null.

    --

    declare @name table(firstName varchar(30), middleName varchar(30), lastName varchar(30))

    insert into @name

    select 'John', 'Q.', 'Public' union all

    select 'John', null, 'Smith' union all

    select null, 'JOHNCORP', null

    --

    select ISNULL(firstName+' ','')+ISNULL(middleName+' ','')+ISNULL(lastName,'')

    from @name

    --

    select ISNULL(lastName+', ','')+ISNULL(firstName+' ','')+ ISNULL(middleName,'')

    from @name

    --

    __________________________________________________

    Against stupidity the gods themselves contend in vain. -- Friedrich Schiller
    Stop, children, what's that sound? Everybody look what's going down. -- Stephen Stills

  • I appreciate that added info. 😎

    I was just thinking about tackling that.

  • You're welcome. I figured you'd get there eventually 😉

    __________________________________________________

    Against stupidity the gods themselves contend in vain. -- Friedrich Schiller
    Stop, children, what's that sound? Everybody look what's going down. -- Stephen Stills

Viewing 5 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply