PL/SQL select into - 如果数据存在

Avi*_*ash 8 plsql

我只有在存在数据时才需要选择局部变量.

SELECT column1 INTO local_variable FROM table1 where column2 = <condition>;
Run Code Online (Sandbox Code Playgroud)

这里如果没有匹配条件的数据,我得到一个没有数据发现的错误.

只有当某些数据符合条件时,我才需要选择局部变量.有一个简单的查询可以解决我的问题.

bpg*_*rgo 14

可能最好的方法是处理no_data_found

begin
  SELECT column1 INTO local_variable 
  FROM table1 where column2 = p_val;
exception
  when no_data_found then
    local_variable := null;
end;
Run Code Online (Sandbox Code Playgroud)

此外,如果您选择主键/唯一键(即column2是唯一的),那么您可以执行一些技巧

SELECT max(column1) INTO local_variable 
  FROM table1 where column2 = p_val;
Run Code Online (Sandbox Code Playgroud)