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

后端 未结 8 741
广开言路
广开言路 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:54

    I would recommend using a cursor. A cursor fetch is always a single row (unless you use a bulk collection), and cursors do not automatically throw no_data_found or too_many_rows exceptions; although you may inspect the cursor attribute once opened to determine if you have a row and how many.

    declare
    v_column my_table.column%type;
    l_count pls_integer;
    cursor my_cursor is
      select count(*) from my_table where ...;
    
    begin
      open my_cursor;
        fetch my_cursor into l_count;
      close my_cursor;
    
      if l_count = 1 then
        select whse_code into v_column from my_table where ...;
      else
        v_column := null;
      end if;
    end;
    

    Or, even more simple:

        declare
        v_column my_table.column%type;
        cursor my_cursor is
          select column from my_table where ...;
    
        begin
          open my_cursor;
            fetch my_cursor into v_column;
            -- Optional IF .. THEN based on FOUND or NOTFOUND
            -- Not really needed if v_column is not set
            if my_cursor%notfound then
              v_column := null;
            end if;
          close my_cursor;
        end;
    

提交回复
热议问题