简体   繁体   中英

What is the correct way to check for null values in PL/SQL?

IF purpose = null THEN
   v_purpose := '';
ELSE
   v_purpose := ' for ' || purpose;
END IF;

When purpose is null, it still goes to the else...why?!

The correct test is

IF purpose IS NULL THEN

This is because NULL is not a value stored in a field. It is an attribute about the field stored elsewhere (but within in the row).

Setting a field to NULL appears to be an ordinary assignment so it is seems perfectly orthogonal to expect testing for it by direct comparison. However, for it to work as it does, I surmise the SQL assignment primitive has a magic hidden aspect which diverts assignment of the special symbol NULL into setting an attribute and not the field.

NULL is a special value in SQL that cannot be compared using the equality operator. You need to use special operators IS and IS NOT when testing if a value is NULL.

Here's a good overview of the idea . And an excerpt:

NOTE: Null In Oracle is an absence of information. A null can be assigned but it cannot be equated with anything, including itself. NULL values represent missing or unknown data. NULL values are not an integer, a character, or any other specific data type. Note that NULL is not the same as an empty data string or the numerical value '0'.

The result of the expression purpose = null is unknown, regardless of what purpose is (see @Paul Sasik's answer for more details). Since it's unknown, it's not necessarily true, so execution bypasses the inside of the IF block and falls into the ELSE block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM