0

我想从存在该列的模式中的每个表中获取名为“YMDH”的列中的不同日期。我想我需要使用嵌套游标(我以前没有做过)并想出了以下代码:

CREATE OR REPLACE PROCEDURE DistinctDates AS 
   sql_statement1 varchar2(200);
   sql_statement2 varchar2(200);
   results varchar2(15);
   ColumnExist integer;
BEGIN
    for cursor_rec in (SELECT * FROM user_objects WHERE object_type='TABLE'
    AND object_name NOT LIKE 'TM%')  loop
    sql_statement1 := 'select count (*) from user_tab_columns where table_name=' || '''' || cursor_rec.object_name || '''' || ' and column_name=' || '''' ||'YMDH'  || '''';
    execute immediate sql_statement1 into ColumnExist;
    if ColumnExist = 1 then
      for inner_cursor_rec in (select distinct(ymdh) from cursor_rec.object_name) loop
         null;
      end loop;
    end if;
    end loop;
END DistinctDates;

SQL Developer 抱怨内部游标的选择语句。错误信息是:

错误(18,32):PL/SQL:SQL 语句被忽略错误(18,70):PL/SQL:ORA-00942:表或视图不存在

所以它不能识别对外部光标的引用。如何将表名(即 cursor_rec.object_name)传递给内部游标?

4

1 回答 1

1

您在不需要的地方使用了动态 SQL,并没有在需要的地方使用它!

The check to see if the table has a column called 'YMDH' can be incorporated into the first query, giving this code:

CREATE OR REPLACE PROCEDURE DistinctDates AS 
   sql_statement varchar2(200);
   rc sys_refcursor;
   ymdh_value ????; -- Appropriate data type
BEGIN
    for cursor_rec in (SELECT t.table_name 
                       FROM user_tables t
                       JOIN user_tab_columns c ON c.table_name = t.table_name
                       WHERE t.table_name NOT LIKE 'TM%'
                       AND c.column_name='YMDH')  
    loop
        sql_statement := 'select distinct(ymdh) from ' || cursor_rec.table_name;
        open rc for sql_statement;
        loop
            fetch rc into ymdh_value;
            exit when rc%notfound;
            null;
        end loop;
        close rc;
    end loop;
END DistinctDates;
于 2012-06-13T09:12:05.327 回答