Three ways to deal with ORACLE NO_DATA_FOUND

In the stored procedure in Oracle, if you need to assign the value in the table to a variable, this method is generally adopted.

SELECT col
INTO v_col
FROM t_table
WHERE condition

 If the data cannot be found, there will be an exception that the data cannot be found

 

 

There are three ways to solve

1. Ordinary exception catch method

2. The way of left join through table association

3. By way of max

 

Method 1 Syntax:

 

  BEGIN
    SELECT col
    INTO v_col
    FROM t_table
    WHERE condition
  EXCEPTION WHEN NO_DATA_FOUND THEN
       do something
  END;

 

Method 2 Syntax:

 

 

select nvl(b.col, custom default value) into v_col
from (select 1 rn from dual) a
left join (
    SELECT col,rownum rn
    FROM t_table
    WHERE condition
) b on a.rn=b.rn

 

 

Method 3 Syntax:

 

SELECT max(col) INTO v_col
FROM t_table
WHERE condition

 

Initialization data

 

 

create table test_sj_salary
(
   id integer primary key,
   name varchar2(100),
   salary integer
);

truncate table test_sj_salary;

insert into test_sj_salary (ID, NAME, SALARY)
values ​​(1, 'Zhang San', 5000);

commit;

 

Demonstration of the three methods

 

declare
  v_salary integer;
begin
  --Processing data not found by exception
  begin
    select tss.salary into v_salary
    from test_sj_salary tss
    where tss.name='Mengniu';
  EXCEPTION WHEN NO_DATA_FOUND THEN
    v_salary := -1;
  end;
   
  dbms_output.put_line('Exception deal '||to_char(v_salary));
  
  --Implemented by table association
  select nvl(b.salary,-2)  into v_salary
  from (select 1 rn from dual) a
  left join (
    select tss.salary,rownum rn
    from test_sj_salary tss
    where tss.name='Erie'
  ) b on a.rn=b.rn;
  
  dbms_output.put_line('Table deal '||to_char(v_salary));
  
  --Processed by max method
  select max(tss.salary) into v_salary
  from test_sj_salary tss
  where tss.name='Bright';
  
  dbms_output.put_line('Max deal '||to_char(v_salary));
end;

 

The author commonly used in daily use is the second method.

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326853625&siteId=291194637