【Oracle】PL/SQL中對空字符串的判斷


寫在最前面:在Oracle 11g中一個空字符串和零個字符是沒有區別的。
今天在使用Oracle編寫PL/SQL程序的時候,發現一個問題,我的表中本身不是空字符串,但是在使用if語句判斷(字段 <> '')的時候,if語句竟然不會生效,很是納悶!
后來查詢相關資料發現:Oracle建議您不要將空字符串視為空字符串
那么具體是怎么回事呢?

1.在Oracle中,將長度為零的字符值視為NULL

以下是一個測試案例,測試Oracle中空字符串與null都被視為null

create table test1(id number, str varchar2(20));
insert into test1 values(1, 'like ''04''');
insert into test1 values(2, 'aa');
insert into test1 values(3, '');
insert into test1 values(4, null);
commit;
-- 查詢語句
select nvl(str, '我是空值') as res from test1;

查詢結果如下:

從查詢結果可以看出,在oracle中,null與空字符串一樣。

2.在PL/SQL中判斷空字符串

直接使用test1表中的列值與空字符串進行判斷

declare 
t_sql varchar2(100);
begin
      select str into t_sql from test1 where id = 1;
      if t_sql <> '' then
         dbms_output.put_line('success!');
      end if;
end;

按照常規邏輯來說,是會打印success的,但是上述PL/SQL塊卻沒有打印結果,表明if語句並沒有生效

2.1 使用nvl函數空值處理

正確的寫法

declare 
t_sql varchar2(100);
begin
      select str into t_sql from test1 where id = 1;
      if nvl(t_sql, 'N') <> 'N' then
         dbms_output.put_line('success!');
      end if;
end;

打印結果:

2.2 使用is not null改寫

declare 
t_sql varchar2(100);
begin
      select str into t_sql from test1 where id = 1;
      if t_sql is not null then
         dbms_output.put_line('success!');
      end if;
end;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM