如何在Oracle中创建IF NOT EXISTS查询?

时间:2014-02-05 12:02:31

标签: sql oracle

我正在尝试在Oracle中创建一个IF NOT EXISTS查询,如下所示:

DECLARE
   cnt   NUMBER;
BEGIN
   SELECT COUNT(*) INTO cnt FROM MY.MYTABLE
    WHERE MYFIELD = 400;

   IF (cnt = 0)
   THEN
      SELECT 'NO ROWS' AS FAIL FROM DUAL;
   ELSE
      SELECT 'SOME ROWS' AS PASS FROM DUAL;
   END IF;
END;

失败了
ORA-06550: line 9, column 7:
PLS-00428: an INTO clause is expected in this SELECT statement
ORA-06550: line 11, column 7:
PLS-00428: an INTO clause is expected in this SELECT statement

为什么,这个查询出了什么问题?

5 个答案:

答案 0 :(得分:5)

使用to为变量赋值。

DECLARE
   cnt   NUMBER;
   res   NVARCHAR2(50);
BEGIN
   SELECT COUNT(*) INTO cnt FROM MY.MYTABLE
    WHERE MYFIELD = 400;

   IF (cnt = 0)
   THEN
      SELECT 'NO ROWS' INTO RES FROM DUAL;
   ELSE
      SELECT 'SOME ROWS' INTO RES FROM DUAL;
   END IF;
END;

您也可以直接将值赋给变量,如

IF (cnt = 0)
       THEN
          res := 'NO ROWS';
       ELSE
          res := 'SOME ROWS';
       END IF;

最好的办法就是使用这个sql

SELECT DECODE(COUNT(*), 0, 'NO ROWS','SOME ROWS')  FROM MY.MYTABLE
    WHERE MYFIELD = 400;

答案 1 :(得分:2)

我更喜欢这种检查存在的方式:

declare
  dummy      varchar2(1);
begin
  select null into dummy
  from MY.MYTABLE
  where MYFIELD = 400
    and rownum = 1;

  dbms_output.put_line('some rows'); -- some rows
exception
  when no_data_found then
    dbms_output.put_line('no rows'); -- no rows
end;

在我看来它更好,因为count()对大量数据的工作速度很慢。

答案 2 :(得分:1)

由于错误消息表明您需要一个变量,您可以在其中选择值:

select 'NO ROWS' as fail into v_status from dual;

当然,您需要先声明变量:

declare
    v_status varchar2(10);
...

但是,将值赋给变量可能更容易:

v_status := 'NO ROWS'

答案 3 :(得分:1)

SQL> create table t (x int);


SQL> insert into t values(1);


SQL> commit;

SQL> set serveroutput on
SQL> declare
  2   res varchar2(10);
  3  begin
  4    select nvl((select 'SOME ROWS' from t where x =1 and rownum <=1), 'NO ROWS')
  5    into res
  6    from dual;
  7    dbms_output.put_line(res);
  8  end;
  9  /
SOME ROWS                                                                       

SQL> declare
  2   res varchar2(10);
  3  begin
  4    select nvl((select 'SOME ROWS' from t where x = 2 and rownum <=1), 'NO ROWS')
  5    into res
  6    from dual;
  7    dbms_output.put_line(res);
  8  end;
  9  /
 NO ROWS

答案 4 :(得分:1)

听起来有点奇怪,但我不想使用 and rownum=1and rownum < 2;并且永远不会将异常用作业务逻辑的一部分。

declare
  cnt   NUMBER;
  res   NVARCHAR2(50);
begin
  select COUNT(*) 
  into cnt
  from MY.MYTABLE
  where MYFIELD = 400
    and rownum < 2;

  IF (cnt = 0) THEN
    RES := 'NO ROWS';
  ELSE
    RES :='SOME ROWS';
  END IF;
end;