日期:2014-05-16  浏览次数:20354 次

不得不记录下Oracle的条件语句

条件语句语法:

?

?

1、单一语句判断:

if  then
  sql 或 pl/sql
end if;

2、if else 判断:

if  then
  sql 或 pl/sql
else
  sql 或 pl/sql
end if;

3、多重判断:

if  then
  sql 或 pl/sql
elsif then
  sql 或 pl/sql
elsif  then
  sql 或 pl/sql
...
end if;

?

?这里的 elsif 是少了个e,我在编辑器里面打了n遍就是不变色,原来他语法少个e... ?无语中。。。

?

?还有pl/sql 判断一个变量是否为空,也比较怪异。这里写下吧。。。

?

?declare?

cc varchar2(10) := '';
begin
  if cc is null then
    dbms_output.put_line('cc is null');
  end if;
  
  if cc = '' then
    dbms_output.put_line('dd is ""');
  end if;
end;

这里输出是:cc is null,这里居然进的是第一个if.不解。。
?

?

declare 
cc varchar2(10) := 's';
begin
  if cc is not null and cc  '' then
    dbms_output.put_line('first if..');
  end if;

  if cc is not null then
    dbms_output.put_line('second if...');
  end if;
end;

这里输出:second if...
?

?

? ?所以在pl/sql 里,判断变量不为空,用 is not null 就可以了,不要在加 <> ?''

?

?

??原来PL/SQL 里,''和null是否相等跟其数据类型相关。看例子。。

?

??declare

  a char(10) := ''; --定长空字符串
  b varchar(20) := ''; --可变长度空字符串
begin
  if a is null then
    dbms_output.put_line('a is null');
  else
    dbms_output.put_line('a is not null');
  end if;
  if b is null then
    dbms_output.put_line('b is null');
  else
    dbms_output.put_line('b is not null');
  end if;
end;

?

?? 结果:

?

?

?

?

a is not null
b is null


--结论就是在pl/sql中,如果是定长(char)的空字符串''和null不一样,可变长度(varchar)的空字符串和null是一样的。
?

?

?

?