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
1
  • SQL Server is implicitly casting '' to an integer, which is 0 (zero). Commented Aug 19, 2014 at 21:26

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Uh, the value '' IS implicitly convertible. It casts as 0. select cast('' as INT) -- returns 0
Thanks.. Looks like the answer was right under my nose.
2

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

1 Comment

have the same issue. Hope somebody will propose better solution then changing source column data type. Read here: stackoverflow.com/questions/39937037/…
-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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.