PL/SQL检查查询是否返回空

Won*_*abo 20 plsql

我正在写一个程序,我需要检查我的选择查询是否返回空记录.(在这个例子中是否没有x,y架子)

我怎样才能做到这一点?

我试过这个:

temp shelves.loadability%TYPE := NULL;
BEGIN

select loadability into temp from shelves where rownumber = x and columnnumber = y;
IF temp IS NOT NULL THEN
/* do something when it's not empty */
ELSE
/* do the other thing when it's empty */
END IF;
Run Code Online (Sandbox Code Playgroud)

但是if的第二个分支从不起作用......

编辑:

哦,这很容易......

temp shelves.loadability%TYPE;
BEGIN

select count(*) into temp from shelves where rownumber = x and columnnumber = y;
IF temp != 0 THEN
/* do something when it's not empty */
ELSE
/* do the other thing when it's empty */
END IF;

END;
Run Code Online (Sandbox Code Playgroud)

Ren*_*ene 15

使用异常处理程序

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;
Run Code Online (Sandbox Code Playgroud)

  • 那是好习惯吗?你正在使用像`condition`这样的`exception`. (18认同)

sch*_*arz 6

异常处理也是我首先想到的,但是如果您不想让自己承担处理所有不同情况的负担,我倾向于使用select count(*) from. count(*) 的好处是它总是返回一些东西(假设你的查询是合法的)。在这种情况下,您可以计数以查看它是否返回 0(没有匹配项)或更多(在这种情况下您可以执行某些操作。

你可以得到这样的东西:

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;
Run Code Online (Sandbox Code Playgroud)


MJB*_*MJB 3

通常,只对存在的记录执行操作更像 SQL。换句话说,您可以为每次出现的匹配执行任务,如果没有出现则不执行该任务。所以你甚至不需要 IF-ELSE 结构。

我不建议使用游标来完成这项工作,因为这与我的第一个建议相反,即您应该更像 SQL 那样进行操作。但如果你必须这样做,那么光标可能会做你想要的。

是的,我意识到这并不能直接回答你的问题。