在IF子句Oracle中执行select / insert语句

时间:2016-07-15 08:19:33

标签: oracle plsql

只有存在表时,我才需要在IF子句中执行一些语句。 但我面临的问题是,即使条件为假,语句也会被执行。

DECLARE
  count_matching_row NUMBER := 0;
  count_matching_tbl NUMBER := 0;
BEGIN
  SELECT COUNT(*)
  INTO count_matching_tbl
  FROM user_tables 
  WHERE LOWER(table_name) = 'tab1';
  IF(count_matching_tbl = 1)
    THEN

      SELECT COUNT (*)
      INTO   count_matching_row
      FROM   test1
      WHERE  ID IN (SELECT ID FROM tab1);

      IF(count_matching_row = 0)
        THEN

          INSERT INTO review_case
            SELECT 
              DISTINCT ID, d,e
            FROM tab1
            WHERE ID IS NOT NULL;

          INSERT INTO review_case_payer
            SELECT 
              a,b,c
            FROM tab1
            WHERE a IS NOT NULL;
         COMMIT;
      END IF;
  END IF;
END;
/

每当我执行这些陈述时,如果表格' tab1'存在它工作正常。 如果表tab1不存在,我会收到错误

" ORA-06550:第13行,第14栏: PL / SQL:ORA-00942:表或视图不存在" 我尝试访问表" tab1"

的每一行都有类似的错误

我尝试使用ref游标但仍然相同,我不能将它用于插入语句。

1 个答案:

答案 0 :(得分:1)

您的错误是由于您使用的表格可能不存在;抛出此错误是因为脚本存在编译问题,而不是数据问题,因此您尝试使用IF的方式不足以处理您的情况。

您需要使用一些动态SQL来处理不存在的对象;例如,请参阅以下内容。

如果该表不存在,则不会执行任何操作:

SQL> select * from tab1;
select * from tab1
              *
ERROR at line 1:
ORA-00942: table or view does not exist


SQL> declare
  2      vCountTab number;
  3  begin
  4      select count(1)
  5      into vCountTab
  6      from user_tables
  7      where table_name = 'TAB1';
  8
  9      if vCountTab = 1 then
 10          execute immediate 'insert into TAB1 values (1, 2)';
 11      end if;
 12  end;
 13  /

PL/SQL procedure successfully completed.

如果表存在,则插入将完成:

SQL> create table tab1(a number, b number);

Table created.

SQL> declare
  2      vCountTab number;
  3  begin
  4      select count(1)
  5      into vCountTab
  6      from user_tables
  7      where table_name = 'TAB1';
  8
  9      if vCountTab = 1 then
 10          execute immediate 'insert into TAB1 values (1, 2)';
 11      end if;
 12  end;
 13  /

PL/SQL procedure successfully completed.

SQL> select * from tab1;

         A          B
---------- ----------
         1          2

SQL>
相关问题