sql—如何使所有列都为空,然后出现异常

ryoqjall  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(337)

如何优化sql查询?
select返回空数据(列)。
如果所有列都为空,则如何在查询中生成异常:

begin  
   select t1.status, t1.curr, t1.amount, t1.serv  
     into stat,curr,amnt,serv  
   from table1 t1  
   where t1.id = 78;   
exception when no_data_found then 
                  result := 1;  
                  stat := 'R';  
          when stat is null and curr is null and amnt is null and serv is null then  
                  result := 1;  
                  stat := 'R';   
end;
oprakyz7

oprakyz71#

如果所有这些变量都声明为 NULL 默认情况下,它们将保持不变 NULL 如果
没有争吵 table1 谁的 ID = 78 ,所以 NO_DATA_FOUND 将被提升,或
实际上有这样一行,但所有这些列的值都是 NULL 这不会导致例外,所以你必须自己提出一个-如果你想的话
在这两种情况下,变量的值将保持不变 NULL 也就是说你可以用这样的方法:
首先是样本数据:

SQL> set serveroutput on
SQL> set ver off
SQL> select * From table1;

        ID S       CURR
---------- - ----------
        22 X          2
        78

具有自定义异常的pl/sql块:

SQL> declare
  2    result   number;
  3    l_status table1.status%type;
  4    l_curr   table1.curr%type;
  5
  6    my_exc   exception;
  7    pragma   exception_init(my_exc, -20001);
  8  begin
  9    select t.status, t.curr
 10      into l_status, l_curr
 11      from table1 t
 12      where t.id = &par_id;
 13
 14    if l_status is null and l_curr is null then
 15       raise my_exc;
 16    end if;
 17
 18    dbms_output.put_line('Everything is OK');
 19
 20  exception
 21    when no_data_found or my_exc then
 22      result := 1;
 23      l_status := 'R';
 24      dbms_output.put_line('Exception has been raised');
 25  end;
 26  /
Enter value for par_id: 22
Everything is OK

PL/SQL procedure successfully completed.

SQL> /
Enter value for par_id: 78
Exception has been raised

PL/SQL procedure successfully completed.

SQL> /
Enter value for par_id: 55
Exception has been raised

PL/SQL procedure successfully completed.

SQL>
gkl3eglg

gkl3eglg2#

向查询中添加所需的 predicate 更容易,因此这两种情况都只需要一个公共异常处理程序:

begin  
   select t1.status, t1.curr, t1.amount, t1.serv  
     into stat,curr,amnt,serv  
   from table1 t1  
   where t1.id = 78
   and (
        t1.status is not null 
     or t1.curr   is not null
     or t1.amount is not null
     or t1.serv   is not null
     );
exception when no_data_found then 
                  result := 1;  
                  stat := 'R';  
end;
/

相关问题