Skip to content
Advertisement

SET statement considers 0 as null

I don’t how to explain my problem but I will try my best to be clear.

I am trying to create a stored procedure that will be used to handle holidays requests. I have two tables:

Table A contains the name of the holiday and the max number of days that can be requested in a year. It goes like this

Table B tracks all the holidays requests and automatically updates the remaining number of days for a specific holiday. After multiple requests, the column ‘Balance’ determines how many days are still available. In the case below, the balance is 0 after the last request.

What I want is that, whenever the balance is 0, a request for a new holiday should not get through. To achieve this, I have applied the following logic (an extract of my procedure):

What I do in this code is:

  • I compute the number of days that a person requests (@quota_requested)
  • I compare it with the quota that is allowed for that holiday (@quota)

  • I compare the number of days requested with the balance for that holiday (@balance)

This logic works very well whenever the balance > 0 but when the balance gets to 0, the following part of the code:

passes NULL to the variable @balance even though the balance = 0. As a result, I am never able to stop the insert when the balance gets to zero and the code starts the balance to the value of the quota due to this part of the code:

I would really like to know what is going on here and why 0 is being treated as NULL. May this be due to the SET function? I changed to SELECT but this didn’t change a thing.

Thank you

Advertisement

Answer

Crystal ball answer

The problem is you think that 0 and '' are different values; with numerical data types you would be wrong. Try this:

You get the result 0 right? That’s because '' was converted the to an int and as an int the value is 0.

That’s why your IF results in true. I’m not honestly sure why you’re comparing an int to a varchar though.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement