PL/SQL选择-如果存在数据 [英] PL/SQL select into - if data exists

查看:52
本文介绍了PL/SQL选择-如果存在数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅当存在数据时,我才需要选择一个局部变量.

I need to select into a local variable only if there exists data.

SELECT column1 INTO local_variable FROM table1 where column2 = <condition>;

如果没有符合条件的数据,我将得到一个找不到数据的错误.

Here if there is no data matching the condition I get a no data found error.

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

I need to select into the local variable only if there is some data matching the condition. Is there a simple query that will solve my problem.

推荐答案

可能最好的方法是处理no_data_found

Probably the best way is to handle 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;

此外,如果您使用主键/唯一键(即column2是唯一键)进行选择,那么您可以做一个技巧

Also, if you are selecting with primary key /unique key (that is column2 is unique) then there is a trick you can do

SELECT max(column1) INTO local_variable 
  FROM table1 where column2 = p_val;

这篇关于PL/SQL选择-如果存在数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆