检查column和table是否都存在,运行根据结果查询

Check if both column and table exist and run queries based on the result

我正在尝试 运行 在 Oracle 数据库上进行一些 SQL 查询,但在 运行 查询之前,我需要检查 table 和列是否都存在。如果 table 存在而列不存在,则 运行 另一个查询:

if table `testtable` exists and if table has column `testcolumn`
    Run a SQL which returns the result 
else if table `testtable` exists but column `testcolumn` not present
    Run a different sql which also returns the result 
else
    print some defined string 

这是一个选项 - 检查 USER_TAB_COLUMNS 的内容,并且 - 根据您找到的内容 - 使用 refcursor 以便 return 结果。

SQL> create or replace function f_test
  2    return sys_refcursor
  3  is
  4    l_cnt number;
  5    cur_r sys_refcursor;
  6  begin
  7    -- 1st test - this one fails
  8    select count(*)
  9      into l_cnt
 10      from user_tab_columns
 11      where table_name = 'EMP'
 12        and column_name = 'DOES_NOT_EXIST';
 13
 14    if l_cnt > 0 then
 15       open cur_r for select ename, job, sal from emp;
 16    end if;
 17
 18    -- 2nd test - this one is OK
 19    select count(*)
 20      into l_cnt
 21      from user_tab_columns
 22      where table_name = 'DEPT'
 23        and column_name = 'DEPTNO';
 24
 25    if l_cnt > 0 then
 26       open cur_r for select dname, loc from dept;
 27    end if;
 28
 29    return cur_r;
 30  end;
 31  /

Function created.

SQL> select f_test from dual;

F_TEST
--------------------
CURSOR STATEMENT : 1

CURSOR STATEMENT : 1

DNAME          LOC
-------------- -------------
ACCOUNTING     NEW YORK
RESEARCH       DALLAS
SALES          CHICAGO
OPERATIONS     BOSTON


SQL>

它必须是某种 dynamic 代码,因为你不能只写 static SELECT 语句选择不存在的列,因为你会得到 ORA-00904: "DOES_NOT_EXIST": invalid identifier 错误。

您可以使用:

DECLARE
  nCount  NUMBER;
BEGIN
  SELECT COUNT(*)
    INTO nCount
    FROM USER_TAB_COLS
    WHERE TABLE_NAME = 'TESTTABLE' AND
          COLUMN_NAME = 'TESTCOLUMN';

  IF nCount > 0 THEN
    -- Run a SQL which returns the result 
  ELSE
    SELECT COUNT(*)
      FROM USER_TABLES
      WHERE TABLE_NAME = 'TESTTABLE';

    IF nCount > 0 THEN
      Run a different sql which also returns the result 
    ELSE
      print some defined string
 END;

您必须向 运行 添加代码 SQL 您想要 运行 的任何内容,并打印您需要的任何消息。

祝你好运。