6

My curiosity always gets the best of me and I've searched online for an explanation to this and came up with nothing (could be because I didn't use the right terms.)

Can someone please explain why SQL Server returns a value of zero (0) when the following is executed, instead of an empty string ('').

    DECLARE @I AS INT
    SET @I = NULL
    SELECT ISNULL(@I, '') -- 0
Ahz
  • 361
  • 1
  • 2
  • 6

3 Answers3

4

As declared here, the second argument to ISNULL is the replacement_value, which "must be of a type that is implicitly convertible to the type of check_expresssion." Implicitly converting '' to INT results in 0.

hunch_hunch
  • 2,283
  • 1
  • 21
  • 26
2

Because @I is declared as an INT, the empty string is implicitly CAST as an integer resulting in a ZERO.

T McKeown
  • 12,971
  • 1
  • 25
  • 32
  • 1
    have the same issue. Hope somebody will propose better solution then changing source column data type. Read here: http://stackoverflow.com/questions/39937037/convert-int-column-values-to-an-empty-string-using-isnull – Data Engineer Oct 08 '16 at 20:31
-2

I know is an old question, but I want to share. The issue here is not because the casting of the ' ' expression, is because the int data type is not null-able and, when you try to SET @I = NULL SQL set the default value zero(0). That's why the statement ISNULL(@I, '') does not find any null in @I and returns its value(0).

Hope it helps somebody out there.

Pedro Lebron
  • 201
  • 2
  • 3