最近在学习pl/sql语句块编程,学到了游标部分,发现一个神奇的动态游标。具体题目如下:打印出所有emp开头的表的ename列数据(每个emp%表均有ename这一列)
总表结构部分如下:
select table_name, column_name
from user_tab_columns
where table_name like 'EMP%' and column_name = 'ENAME'
注意表名和列名必须大写(别问我咋意识到的,我会告诉你我苦苦找了这个bug一个半小时吗。手动白眼)
题目要求是找出TABLE_NAME是emp开头的表,COLUMN_NAME为ename的列。
declare
v_table_name varchar2(30);
v_column_name varchar2(30);
v_column_data varchar2(40);
cursor cur_sel_table is --建立查表名的游标
select table_name, column_name
from user_tab_columns
where table_name like 'EMP%'
and column_name = 'ENAME';
type cursor_type is ref cursor;--定义动态游标的类型变量
--除了cursor_type是随意起的,其余全是关键字
cur cursor_type; --定义一个动态游标类型的变量cur
begin
open cur_sel_table;
loop --循环遍历表名
fetch cur_sel_table
into v_table_name, v_column_name;
dbms_output.put_line(v_table_name || ',' || v_column_name);
exit when cur_sel_table%notfound;
open cur for 'select ' || v_column_name || ' from ' || v_table_name;
--开始内循环
loop --循环遍历列名里的数据
fetch cur
into v_column_data;
dbms_output.put_line(v_column_data);
exit when cur%notfound;
end loop;
--结束内循环
close cur;
dbms_output.put_line(null); --为了输出结果美观,没啥实际意义
dbms_output.put_line(null);
dbms_output.put_line(null);
exit when cur_sel_table%notfound;
end loop;
close cur_sel_table;
end;
结果的截图: