首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >PL/SQL检查查询是否返回空

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

Stack Overflow用户
提问于 2011-05-11 03:00:24
回答 4查看 96.2K关注 0票数 27

我正在编写一个过程,我需要检查我的select查询是否返回了空记录。(在此示例中是否没有x,y工具架)

我该怎么做呢?

我试过这个:

代码语言:javascript
复制
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;

但是if的第二个分支永远不会起作用...

编辑:

哦,太简单了.

代码语言:javascript
复制
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;
EN

回答 4

Stack Overflow用户

发布于 2011-05-11 17:41:00

使用异常处理程序

代码语言:javascript
复制
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;
票数 20
EN

Stack Overflow用户

发布于 2013-09-25 23:25:35

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

你可以得到类似这样的东西:

代码语言:javascript
复制
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;
票数 4
EN

Stack Overflow用户

发布于 2011-05-11 03:04:15

通常,只为已存在的记录做工作更像SQL。换句话说,您可以在每次匹配时执行任务,如果没有匹配,则不执行该任务。因此,您甚至不需要IF-ELSE构造。

我不建议使用游标来完成这项工作,因为这将与我最初建议的更像SQL的做法背道而驰。但是如果你必须这样做,那么光标可能会做你想做的事情。

是的,我知道这并没有直接回答你的问题。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5955025

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档