Addition with NULL values

后端 未结 5 820
傲寒
傲寒 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: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.

提交回复
热议问题