[英]Oracle Nested cursors
I want to get the distinct dates in a column called "YMDH" from each table in a schema where that column exists. 我想从该列所在的架构中的每个表的“ YMDH”列中获取不同的日期。 I figured that I needed to use nested cursors (something I've not done before) and came up with the following code:
我认为我需要使用嵌套游标(以前没有做过的事情),并想出了以下代码:
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 is complaining about the select statement for the inner cursor. SQL Developer抱怨内部游标的select语句。 The error message is:
错误消息是:
Error(18,32): PL/SQL: SQL Statement ignored Error(18,70): PL/SQL: ORA-00942: table or view does not exist
错误(18,32):PL / SQL:忽略了SQL语句错误(18,70):PL / SQL:ORA-00942:表或视图不存在
So it's not recognizing the reference to the outer cursor. 因此,它无法识别对外部光标的引用。 How do I pass the table name (which is the cursor_rec.object_name) to the inner cursor?
如何将表名(cursor_rec.object_name)传递给内部游标?
You have used dynamic SQL where it is not needed, and have not used it where it is needed! 您已经在不需要的地方使用了动态SQL,也没有在不需要的地方使用了它!
The check to see if the table has a column called 'YMDH' can be incorporated into the first query, giving this code: 可以将检查表是否包含名为“ 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.