PL / SQL select - if data exists

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

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

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

I need to select a local variable only if there is some data that matches the condition. There is a simple request that will help solve my problem.

+6
source share
2 answers

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; 

Also, if you select using the primary key / unique key (which is unique to column2), then there is a trick you can do

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

Well ... make a count before you make a choice. Or just throw a no_data_found exception.

You can open the cursor and get lines, make a counter, and if it is greater than 0, then do your stuff with this entry

+1
source

Source: https://habr.com/ru/post/896686/


All Articles