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

后端 未结 8 685
广开言路
广开言路 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 14:51

    I use this syntax for flexibility and speed -

        begin
        --
        with KLUJ as
        ( select 0 ROES from dual
           union 
          select count(*) from MY_TABLE where rownum = 1
        ) select max(ROES) into has_rows from KLUJ;
        --
        end;
    

    Dual returns 1 row, rownum adds 0 or 1 rows, and max() groups to exactly 1. This gives 0 for no rows in a table and 1 for any other number of rows.

    I extend the where clause to count rows by condition, remove rownum to count rows meeting a condition, and increase rownum to count rows meeting the condition up to a limit.

提交回复
热议问题