Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Firebird Null guide.pdf
Скачиваний:
8
Добавлен:
23.08.2013
Размер:
78.64 Кб
Скачать

Firebird Null Guide

NULL in if statements

If the test expression of an if statement resolves to NULL, the then clause is skipped and the else clause (if present) executed. But beware! The expression may behave like false in this case, but it doesn't have the value false. It's still NULL, and weird things may happen if you forget that. The following examples explore some of the fiendish workings of NULL in if statements:

if (a = b) then MyVariable = 'Equal';

else

MyVariable = 'Not equal';

If a and b are both NULL, MyVariable will yet be “Not equal” after executing this code. The reason is that the expression “a = b” yields NULL if at least one of them is NULL. With the test expression NULL, the then block is skipped, and the else block executed.

if (a <> b) then MyVariable = 'Not equal';

else

MyVariable = 'Equal';

Here, MyVariable will be “Equal” if a is NULL and b isn't, or vice versa. The explanation is analogous to that of the previous example.

if (not (a <> b)) then MyVariable = 'Equal';

else

MyVariable = 'Not equal';

This one looks like it should give the same results as the previous example, doesn't it? After all, we've inverted the test expression and swapped the then and else clauses. And indeed, as long as neither variable is NULL, both code fragments are equivalent. But as soon as a or b becomes NULL, so does the entire test expression, the else clause is executed, and the result is “Not equal”.

Note

Of course we're aware that this third example is fully equivalent to the first. We've merely included it to stress once more that not(NULL) is NULL. So, in situations where the test expression resolves to NULL, not() doesn't invert it.

Testing if something is NULL

In light of the havoc that NULL can wreak, you will often want to know whether something is NULL before you use it in an expression. To some, the obvious test would seem to be

if (A = NULL) then...

and indeed there are database management systems that support this syntax to determine nullness. But the SQL standard doesn't allow it, and neither does Firebird. In versions prior to 2.0 this entire syntax is even illegal. From 2.0 onward it is permitted, but the comparison always returns NULL, regardless of A's state and value. It is therefore worthless as a nullness test - what we need is a clear true or false result.

8