How to select into a variable in PL/SQL when the result might be null?

后端 未结 8 687
广开言路
广开言路 2020-12-07 14:08

Is there a way in to just run a query once to select into a variable, considering that the query might return nothing, then in that case the variable should be null.

相关标签:
8条回答
  • 2020-12-07 15:01

    From all the answers above, Björn's answer seems to be the most elegant and short. I personally used this approach many times. MAX or MIN function will do the job equally well. Complete PL/SQL follows, just the where clause should be specified.

    declare v_column my_table.column%TYPE;
    begin
        select MIN(column) into v_column from my_table where ...;
        DBMS_OUTPUT.PUT_LINE('v_column=' || v_column);
    end;
    
    0 讨论(0)
  • 2020-12-07 15:04

    COALESCE will always return the first non-null result. By doing this, you will get the count that you want or 0:

    select coalesce(count(column) ,0) into v_counter from my_table where ...;
    
    0 讨论(0)
提交回复
热议问题