IsNULL and Coalesce proper usage

后端 未结 3 519

As we have two options to intercept the null values coming from database...

  1. ISNull
  2. Coalesce

Following ar

3条回答
  •  孤城傲影
    2021-01-22 03:17

    begin humor: The 1st, the 2nd will never work it's spelled wrong :D END humor

    ---Cleaned up response---

    Features of isNull(value1,value2)

    • Only supports 1 valuation, if the first is null, the 2nd will be used, so if its null too you get null back!
    • is non-ANSI standard. Meaning if database portability is an issue, don't use this one
    • isnull(value1,value2) will return the datatype for Value1
    • will return the datatype for the selected value and fail when implicit conversions can't occur

    Features of Coalesce(Value1, Value2, value3, value...)

    • Supports multiple valuations of Null; basically will pull in the first non-null value from the list. if all values are null in list, null is returned.
    • is ANSI-standard meaning database portability shouldn't be an issue.
    • will return the datatype for the selected value and fail if all fields in the select do not return the same datatype.

    So to answer the question directly: It depends on the situation if you need to develop SQL that

    • is DB independent; coalesce is more correct to use.
    • allows for multiple evaluations; coalesce is more correct (of course you could just embed isnull over and over and over...) but put that under a performance microscope, and coalesce may just win. (i've not tested it)
    • are you using a db engine that supports isNull? (if not use coalesce)
    • how do you want type casting handled? implicitly or not.

    ---ORIGINAL------ is null only supports 2 evaluations

    coalesce supports many more... coalesce (columnName1, ColumnName2, ColumnName3, '')

    coalesce returns datatype similar to that of case evaluation, whereas isnull returns datatype of first in list. (which I found interesting!)

    As to when to use which. you'd have to investigate by looking at execution plan of both on SQL 2008 and 2005, different versions different engines different ways to execute.

    Furthermore coalesce is ansii standard, isnull is engine specific. Thus if you want greater portability between dbengines use coalesce.

    More info here aspfaq or here msdn blog

提交回复
热议问题