Best Way To Add Columns With Null Values in TSQL

  • What's the best way to add columns which have null values in TSQL? Is there a more efficient way than using a CASE statement?

  • Can you clarify the question? Are you talking about adding a column to a table or to a result set?

    Jared
    CE - Microsoft

  • I think the OP means this:

    SELECT CASE WHEN Col1 IS NULL THEN 0 ELSE Col1 END + CASE WHEN Col2 IS NULL THEN 0 ELSE Col2 END ?

    SELECT ISNULL(Col1, 0) + ISNULL(Col2, 0) or COALESCE(Col1, 0) + COALESCE(Col2, 0) both work, couldn't comment on their relative speeds though.

  • Gazareth (8/6/2012)


    I think the OP means this:

    SELECT CASE WHEN Col1 IS NULL THEN 0 ELSE Col1 END + CASE WHEN Col2 IS NULL THEN 0 ELSE Col2 END ?

    SELECT ISNULL(Col1, 0) + ISNULL(Col2, 0) or COALESCE(Col1, 0) + COALESCE(Col2, 0) both work, couldn't comment on their relative speeds though.

    There was a discussion on this awhile back: http://www.sqlservercentral.com/Forums/Topic832742-392-1.aspx

    Jared
    CE - Microsoft

  • isnull did the trick, thanks

  • Take a look at Coalesce while you're getting into this. It has advantages over IsNull, in that it can have more than 2 arguments. Plus, it is part of the ANSI/ISO SQL standard, and IsNull isn't, which is a minor advantage, but is one.

    - Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
    Property of The Thread

    "Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon

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

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