问题
In trying to test whether a variable has been defined, I discovered that the IF, IFNULL, and COALESCE statements return simply BLOB rather than the value I expected when (a) the variable has not been defined or (b) it has been explicitly set to NULL before being assigned a value in the session. I've verified this in MySQL versions 5.7 and 8.0.
SELECT IF(@p IS NULL, 'is null', 'not null'); # 'is null'
SELECT IF(@p IS NULL, 'is null', @p); # BLOB
SELECT IFNULL(@p, 'is null'); # BLOB
SELECT COALESCE(@p, 'is null'); # BLOB
The first statement acts as I expected, but the others return BLOB rather than 'is null'. The behavior is the same if preceded by SET @p = NULL.
On the other hand, if you do any of these, the above statements will all return 'is null', that is, they act as expected with a null value.
SET @p = NULL + 1
rather thanSET @p = NULL
before testing.SET @p = 5; SET @p = NULL;
That is, first set a non-null value, then set to nullSELECT COALESCE(@p+1, 'is null')
# use expression @p+1 instead of @p.
Presumably, these three somehow set a type for NULL. In any case, an undefined variable or variable only defined as NULL have a different kind of NULL than those with a history of typing (?).
What is the underlying principle that explains this behavior? Is it simply an untyped NULL acts differently than a typed NULL, and those statements don't work with untyped ones?
Note: I know that that a workaround for this in a procedure, in order to detect undefined variables, can be
IF @p IS NULL
SET @p = default_value
END IF;
and it looks as if I can also use COALESCE(@p+1,default_value)
. But I'm interested in the explanation for why this is needed. Thanks.
来源:https://stackoverflow.com/questions/62413075/unexpected-blob-results-with-mysql-testing-null-variable-with-ifnull-coalesce