PL/SQL check if query returns empty

前端 未结 4 1712
闹比i
闹比i 2021-01-03 19:58

I\'m writing a procedure, and i need to check whether my select query returned an empty record or not. (In this example whether there is no x,y shelf)

How can i do t

相关标签:
4条回答
  • 2021-01-03 20:31

    Exception handling would be the first thing I think of too, but if you don't want to burden yourself with handling all the different cases, I tend to use a select count(*) from. The nice thing with count(*) is that it ALWAYS returns something (assuming your query is legal). In this case you could count to see if it returns 0 (no matches) or more (in which case you can do something.

    You could get something like this:

    declare
      v_count number := 0;
    begin
      select count(*) into v_count from table where condition;
    
      if v_count = 0 then
          --do something
      else
          --do something else
      end if;
    end;
    
    0 讨论(0)
  • 2021-01-03 20:33

    It is generally more SQL-like to just do the work for the records that exist. In other words, you could perform your task for each occurrence of the match, and if there are no occurrences you don't do it. So you would not even need the IF-ELSE construct.

    I won't recommend using a cursor to do the work, because that would be counter to my first suggestion that you do it more SQL-like. But if you have to do it this way, then a cursor might do what you want.

    And yes, I realize that does not answer your question directly.

    0 讨论(0)
  • 2021-01-03 20:38

    Use an exception handler

    Begin
      select column
      into variable
      from table
      where ...;
    
      -- Do something with your variable
    
    exception
     when no_data_found then
        -- Your query returned no rows --
    
     when too_many_rows
        -- Your query returned more than 1 row --
    
    end;
    
    0 讨论(0)
  • 2021-01-03 20:40

    catch first not wanted condition and use count(1) because count(*) actually trying to count something and add rownum=1, you need only one first not matching condition. i use this statement.

           declare
          v_check number;
        begin
          select count(1) into v_check 
    from table
     where condition(something not wanted) AND rownum=1;
    
          if v_check = 0 then 
               --do something else
          elsif v_check = 1 --dont want theat
             rise some error or more..
          end if;
        end;
    

    For you just

    select count(1) into v_check from dual where exists (select count(1) 
        from table
         where condition AND rownum=1);
    
    if v_check = 0 then --nothing found
                     something...
              elsif v_check = 1 --found something
                something...
              end if;
            end;
    
    0 讨论(0)
提交回复
热议问题