Addition with NULL values

后端 未结 5 777
傲寒
傲寒 2020-12-10 11:00

In a stored procedure (Oracle in my case), I want to add some values to an existing record. Problem is that both the existing value and the value to be added can be null. I

相关标签:
5条回答
  • 2020-12-10 11:14

    You can also use ISNULL, so if you have 3 values

    isnull(val1,0)+isnull(val2,0)+isnull(val3,0)
    

    which ever column will have a NULL will use a 0, otherwise its original value.

    0 讨论(0)
  • 2020-12-10 11:23

    If you want to add a and b and either may be null, you could use coalesce, which returns the first non-null parameter you pass it:

    coalesce(a+b, a, b)
    

    So in this case, if neither parameter is null, it will return the sum. If only b is null, it will skip a+b and return a. If a is null, it will skip a+b and a and return b, which will only be null if they are both null.

    If you want the answer to be 0 rather than null if both a and b are null, you can pass 0 as the last parameter:

    coalesce(a+b, a, b, 0)
    

    Do consider @erwins answer - null might not be the right thing to be using.

    0 讨论(0)
  • 2020-12-10 11:24

    In SQL, Null is supposed to be a state that says "I don't know".

    If you don't know how much b is, then you also do not know how much a+b is, and it is misleading to pretend that a+b=a in that case.

    0 讨论(0)
  • 2020-12-10 11:25

    In SQL terms, when adding numbers, a result of NULL means there were no non-null numbers added.

    This suggests that a sensible answer in SQL terms would be

    CASE WHEN A IS NULL AND B IS NULL THEN NULL ELSE ISNULL(A, 0) + ISNULL(B, 0) END

    0 讨论(0)
  • 2020-12-10 11:30

    I accomplished it this way:

    coalesce("Column1",0.00) + coalesce("Column2",0.00)
    

    I'm working with front end high level execs.... They don't understand why NULL and 0 aren't handled the same way.

    In my case it works, just replacing NULLs with 0.00... may not in all though :)

    0 讨论(0)
提交回复
热议问题