如何在IF语句中使用Oracle中不存在的表

yhqotfr8  于 2023-06-29  发布在  Oracle
关注(0)|答案(2)|浏览(156)

我在Oracle中有要求,我必须首先检查文件夹表是否存在,然后重新检查文件夹表的特定值。如果不存在,则显示错误
我得到PL/SQL:ORA-00942:第14行的表或视图不存在,因为文件夹表不可用。

DECLARE
    own   VARCHAR2(200);
    l_cnt INTEGER;
BEGIN
SELECT sys_context( 'userenv', 'current_schema' ) INTO own FROM dual;
SELECT count(*)
INTO l_cnt
FROM ALL_TABLES
WHERE Table_name = upper('Folder')
AND OWNER        = own;
IF( l_cnt       > 0) THEN
    SELECT count(*)
    INTO l_cnt
    FROM Folder
    Where id = 3;
        IF( l_cnt       > 0) THEN
            DBMS_OUTPUT.PUT_LINE ('Value exists');
        ELSE
            DBMS_OUTPUT.PUT_LINE ('Value does not exist');
        END IF;
ELSE
    DBMS_OUTPUT.PUT_LINE ('Folder does not exist');
END IF;
END;

有人能帮助我如何使用数据库中不可用的表来重新检查IF语句中的数据吗?

30byixjq

30byixjq1#

你不能从一个在“编译”时不存在的表中SELECT,因为PL/SQL引擎会检查该表是否存在,如果不存在,就会引发ORA-00942: table or view does not exist
如果你想从一个可能存在也可能不存在的表中执行SELECT,那么你需要通过将它 Package 在EXECUTE IMMEDIATE中来推迟执行该语句,直到运行时。
此外,您不需要先检查表是否存在;只要尝试查询表并捕获异常,如果它不存在:

DECLARE
  l_cnt INTEGER;
  table_does_not_exist EXCEPTION;
  PRAGMA EXCEPTION_INIT(table_does_not_exist, -942);
BEGIN
  EXECUTE IMMEDIATE 'select count(*) from Folder where id = 3' INTO l_cnt;

  IF (l_cnt > 0) THEN
    DBMS_OUTPUT.PUT_LINE('Value exists');
  ELSE
    DBMS_OUTPUT.PUT_LINE('Value does not exist');
  END IF;
EXCEPTION
  WHEN table_does_not_exist THEN
    DBMS_OUTPUT.PUT_LINE('Folder does not exist');
END;
/

fiddle

u4vypkhs

u4vypkhs2#

您可以使用 EXECUTE IMMEDIATE 对文件夹表运行查询:

declare
  own   varchar2(200);
  l_cnt integer;
begin
  select sys_context('userenv',
                    'current_schema')
    into own
    from dual;
  select count(*)
    into l_cnt
    from ALL_TABLES
   where Table_name = upper('Folder')
     and OWNER = own;
 if (l_cnt > 0) then
    execute immediate 'select count(*) from Folder where id = 3' into l_cnt;
    if (l_cnt > 0) then
      DBMS_OUTPUT.PUT_LINE('Value exists');
    else
      DBMS_OUTPUT.PUT_LINE('Value does not exist');
    end if;
else
  DBMS_OUTPUT.PUT_LINE('Folder does not exist');
end if;

结束;
请参阅有关EXECUTE IMMEDIATE的Oracle文档

相关问题