我可以在PLSQL中执行以下操作吗?
if (some_query) then
dbms_output.put_line('Your query returned at least 1 row.');
else
dbms_output.put_line('Your query returned no rows.');
end if;
我的用例是我想检查数据库中是否已存在某个值。如果该值已经存在,那么我将做一些不同于该值根本不存在的事情。
答案 0 :(得分:4)
如果检查是否存在记录,则可以根据键从源表中选择COUNT(*),因为它总是会返回一个值,您可以检查:
SQL> set serverout on
SQL> DECLARE
2 v_check NUMBER;
3 BEGIN
4 SELECT COUNT(*)
5 INTO v_check
6 FROM DUAL
7 WHERE DUMMY = 'X'
8 AND ROWNUM = 1;
9
10 if (v_check = 0) then
11 dbms_output.put_line('Your query returned no rows.');
12 else
13 dbms_output.put_line('Your query returned at least 1 row.');
14 end if;
15 END;
16 /
Your query returned at least 1 row.
PL/SQL procedure successfully completed.
SQL>
答案 1 :(得分:3)
你必须做类似
的事情BEGIN
SELECT 1
INTO l_foo
FROM dual
WHERE EXISTS (<<some query>>);
dbms_output.put_line( 'Your query returned at least 1 row' );
EXCEPTION
WHEN no_data_found
THEN
dbms_output.put_line( 'Your query returned 0 rows' );
END;
如果查询不是太昂贵,那么如果您做一些更简单的事情,它将几乎同样有效并且可能更容易维护
SELECT COUNT(*)
INTO l_foo
FROM (<<some query>>)
WHERE rownum = 1;
IF( l_foo = 1 )
THEN
dbms_output.put_line( 'Your query returned at least row.' );
ELSE
dbms_output.put_line( 'Your query returned 0 rows.' );
END IF;
答案 2 :(得分:2)
完全一样,没有。但有几种方法可以伪造它:
如果你只需要做一件事就可以在隐式游标中进行,确认你的值是否存在。
for i in ( some_query ) loop
do_something;
end loop;
您还可以在此设置值并在if
for i in ( some_query ) loop
result := True;
end loop;
if result then
do_something;
else
do_something_else;
end if;
或者您可以使用显式游标并捕获将要引发的no_data_found
错误
declare
cursor c_blah is
select my_value
from my_table
where id = my_id
;
my_value varchar2(4000);
begin
open c_blah(my_id);
fetch c_blah into my_value;
close c_blah;
do_something;
exception when no_data_found then
do_something_else;
end;
答案 3 :(得分:1)
由于您的用例在查询返回一行或一千行的情况下表现相同,请使用EXISTS
:
DECLARE
l_dummy VARCHAR2(1);
BEGIN
SELECT NULL
INTO l_dummy
FROM DUAL
WHERE EXISTS (SELECT NULL
FROM <some_query>);
DBMS_OUTPUT.PUT_LINE('Your query returned at least one row.');
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Your query returned no rows.');
END;