Plsql PL/SQL检查查询是否返回空
我正在编写一个过程,需要检查select查询是否返回空记录。 (在本例中,是否没有x、y托架) 我该怎么做 我试过这个:Plsql PL/SQL检查查询是否返回空,plsql,Plsql,我正在编写一个过程,需要检查select查询是否返回空记录。 (在本例中,是否没有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 empt
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的第二个分支永远不起作用
编辑:
哦,太容易了
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;
一般来说,SQL更喜欢只对存在的记录进行处理。换句话说,您可以为每次匹配执行任务,如果没有匹配,则不执行。因此,您甚至不需要IF-ELSE构造 我不建议使用游标来完成这项工作,因为这与我的第一个建议背道而驰,我建议您更像SQL。但是,如果必须这样做,那么光标可能会执行您想要的操作
是的,我意识到这并不能直接回答您的问题。使用异常处理程序
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;
异常处理也是我想到的第一件事,但是如果您不想处理所有不同的情况,我倾向于使用
中的选择count(*)。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;
catch first not want条件并使用count(1),因为count(*)实际上试图计算某些内容并添加rownum=1,您只需要一个first not want条件。我使用此语句
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;
为了你
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;
但是我必须做一个任务,如果没有这样一个架子…我必须插入一个新架子上的元组。如果不清楚,很抱歉。那么,有什么建议我可以这样做吗?@WonderCsabo:对不起,我没有及时回到问题上来。很高兴你解决了它。选择count(*)也不是很好的检查行的方法。请参阅下面的我的答案以获得更优化的方法。您的编辑应该是您问题的答案。这是一个好的做法吗?您使用的是一个异常
,就像一个条件
。不是,这不是一个好的做法,请参阅“提示”在错误捕获部分:它被称为异常处理。这是plsql的工作方式。我认为这不是一个好方法。因为,根据定义,异常条件是程序不知道如何处理的情况。在这种情况下,最安全的做法是优雅地终止进程/函数/过程。Impleme从良好的编程实践来看,在优雅关闭例程中重新定义业务规则不是一个好主意!在PLSQL中执行select…into时,您必须期望得到0、1或更多结果。并且您需要处理这些情况。当然,您可以进行select计数(*)首先,但没有100%的保证在稍后执行select into时数据没有更改。在PLSQL中处理未找到的数据和太多的行异常是处理select..into查询的一种非常标准的方法。