如果条件,检查变量为空

时间:2017-03-17 10:13:23

标签: oracle plsql

CREATE OR REPLACE FUNCTION func
RETURN varchar2 AS
myvar INT;
BEGIN
  select 1 into myvar  from dual where 1=2;
  IF  myvar  IS NULL THEN
    return 'n';
  ELSE
    return 'y';
  END IF;
END;


SELECT  func() FROM DUAL;

为什么这个函数返回NULL而不是字符串“n”?

1 个答案:

答案 0 :(得分:2)

因为您从no_data_found获得了一个例外(insert into此处不会获得任何数据,这会引发异常)并且好像没有返回=>> null返回:

CREATE OR REPLACE FUNCTION func
RETURN varchar2 AS
myvar INT;
BEGIN
  select 1 into myvar  from dual where 1=2;
  IF  myvar  IS NULL THEN
    return 'n';
  ELSE
    return 'y';
  END IF;
-- This will execute now
exception 
   when no_data_found then
      return 'no_data_found';
   -- Just to note, when it has 2 rows+ that´s the other possible exception here
   when to_many_rows then
      return 'to_many_rows';
END;
/
SELECT func() FROM DUAL;

O / P

no_data_found