Как сделать, чтобы если все столбцы были пустыми, то исключение - PullRequest
1 голос
/ 12 июля 2020

Как оптимизировать запрос 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;

Ответы [ 2 ]

1 голос
/ 12 июля 2020

В запрос проще добавить обязательные предикаты, поэтому вам понадобится только один общий обработчик исключений для обоих случаев:

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;
/
1 голос
/ 12 июля 2020

Если все эти переменные объявлены как 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>
...