PLSQL中NULL值的影响

本文深入探讨了Oracle数据库中NULL值的特性与处理方式,包括NULL与空字符串的区别、NULL值在条件判断中的特殊规则,以及如何正确处理NULL值避免逻辑错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是NULL?

在Oracle中,一个缺失值由NULL来表示。 空字符串:‘’;

‘’ is null 该表达式为true;

declare 
  -- Local variables here
 
begin
  -- Test statements here
  if '' is null then 
      dbms_output.put_line(1);
      end if;
end;

运行结果:

在PL/SQL中,给一个varcahr2(n)的变量赋值长度为0的字符串,也能得到NULL。

declare 
  -- Local variables here
 str varchar2(1) := '';
begin
  -- Test statements here
  if str is null then 
      dbms_output.put_line(2);
      end if;
end;

运行结果:

对这个结果是不是和吃惊!

Oracle数据库会把空字符串当做NULL处理。

declare
  empty_varchar2 varchar2(10) := '';
  empty_char     char(10) := '';
begin
  -- Test statements here
  if empty_varchar2 is null then
    dbms_output.put_line('empty_varchar2 is NULL');
  end if;

  if '' is null then
    dbms_output.put_line(''''' is NULL');
  end if;

  if empty_char is null then
    dbms_output.put_line('empty_char is NULL');
  elsif empty_char is not null then
    dbms_output.put_line('empty_char is not NULL');
  end if;

end;

运行结果:

char类型的变量不会被看作是 NULL, 因为char类型是一个固定长度的字符串,不会为空,会用空格去填补一直到达到10个字符串为止。 

varchar2类型的变量是NULL,是一个长度为0的文本字符串,在if语句中的判断要注意,因为NULL永远不等于NULL

if user_entered_name <> user_from_database then 

如果用户输入是空字符串,这个if永远得不到true。 因为NULL永远不等于NULL

解决空字符串就是NULL的方法:

if (user_entered_name <> user_from_database) or (user_entered_name is null) then 

NULL对条件判断的影响

布尔表达式返回的结果是三种:TRUE、FALSE、NULL

示例:工资超过4000的员工获得奖金,而其它员工将没有奖金

错误代码:

declare
  -- Local variables here
  salary number := 4001;
begin
  -- Test statements here
  if salary <= 4000 then
    dbms_output.put_line('没有奖金');
  else
    dbms_output.put_line('奖金500');
  end if;
end;

运行结果:

但,如果当员工的工资为NULL的时候,会执行奖金为500的情况。

declare
  -- Local variables here
  salary number := null;
begin
  -- Test statements here
  if salary <= 4000 then
    dbms_output.put_line('没有奖金');
  else
    dbms_output.put_line('奖金500');
  end if;
end;

运行结果:

所以条件判断中要考虑NULL值的存在。

NULL语句

null;

短路估计

当第一个操作数是FALSE或NULL的时候,立即执行的其它分支

if condition1 and condition2 then 
  ...
  else
    ...
    end if;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值