我有一个关于ORACLE的问题,我写了一个PLSQL CODE来检查表是否存在,如果存在,那么我从该表中选择一些内容。.pseudocode类似于:
如果(表存在)
从表中选择...。
问题是,即使表条件不存在且select语句从不执行,即使表不存在,我也总是会收到错误消息。
我认为这是因为在编译时检查了我的代码:“select from ..”,如果表不存在,则会打印错误。我该如何解决这样的问题?..这是我的代码的样子(我使用了通用名称):
DECLARE
v_table_exists NUMBER;
BEGIN
SELECT NVL(MAX(1), 0)
INTO v_table_exists
FROM ALL_TABLES
WHERE TABLE_NAME = 'TABLE_TEST';
IF v_table_exists = 1 THEN
INSERT INTO MY_TABLE(COLUMN1, COLUMN2, COLUMN3, COLUMN4)
SELECT 1234,
5678,
T.COLUMN_TEST1,
T.COLUMN_TEST2
FROM TABLE_TEST T
WHERE T.FLAG = 1;
END IF;
END;
最佳答案
问题的确切原因在于,您的过程因为引用了不存在的对象而没有被编译;为此,您可能需要一些动态SQL;例如:
create or replace procedure checkTable is
vCheckExists number;
vNum number;
begin
-- check if the table exists
select count(1)
into vCheckExists
from user_tables
where table_name = 'NON_EXISTING_TABLE';
--
if vCheckExists = 1 then
-- query the table with dynamic SQL
execute immediate 'select count(1) from NON_EXISTING_TABLE'
into vNum;
else
vNum := -1;
end if;
dbms_output.put_line(vNum);
end;
即使表不存在,该过程也会编译;如果立即致电,您将获得:
SQL> select count(1) from NON_EXISTING_TABLE;
select count(1) from NON_EXISTING_TABLE
*
ERROR at line 1:
ORA-00942: table or view does not exist
SQL> exec checkTable;
-1
PL/SQL procedure successfully completed.
然后,如果您创建表并再次调用该过程:
SQL> create table NON_EXISTING_TABLE(a) as select 1 from dual;
Table created.
SQL> exec checkTable;
1
PL/SQL procedure successfully completed.
与我显示
SELECT
的方式相同,您可以执行UPDATE
或所需的任何SQL查询。如果您执行的操作不同于SELECT
,则必须删除INTO
子句。例如,假设您需要插入另一个表中,则应以这种方式编辑以上代码:
if vCheckExists = 1 then
execute immediate 'insert into target(a, b, c) select a, 1, 100 from NON_EXISTING_TABLE';
end if;