我希望从该列所在的架构中的每个表中获取名为“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抱怨内部游标的select语句。错误消息是:
错误(18,32):PL / SQL:忽略SQL语句 错误(18,70):PL / SQL:ORA-00942:表或视图不存在
所以它没有识别对外部光标的引用。如何将表名(cursor_rec.object_name)传递给内部游标?
答案 0 :(得分:1)
您已经在不需要的地方使用了动态SQL,并且在需要它的地方没有使用它!
检查表是否有一个名为'YMDH'的列可以合并到第一个查询中,给出以下代码:
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;