下面是一步一步的代码,你可以在这个 SQLFiddle中测试它。
用于测试的示例表:
create table t1(n number)
/
create table t2(n number)
/
create table t13(n number)
/
insert into t1(n) values(1)
/
insert into t2(n) values(2)
/
insert into t13(n) values(13)
/
声明用作选择结果的类型,与具有动态名称的表的行类型相同:
create or replace type t_row as object(n number)
/
create or replace type t_rowlist as table of t_row
/
搜索最后一个表并从中选择数据到集合中的函数,然后将集合作为表数据返回:
create or replace function get_last_data return t_rowlist
as
v_table varchar2(30);
v_rows t_rowlist;
begin
select table_name into v_table from (
select * from user_tables where table_name like 'T%'
order by lpad(substr(table_name,2),40,'0') desc
)
where rownum = 1;
execute immediate 'select t_row(n) from '|| v_table
bulk collect into v_rows;
return v_rows;
end;
/
根据函数数据创建视图:
create or replace view last_data_view as
select * from table(get_last_data)
/
仅当动态表没有大量数据时,这才有效。
否则最好使用流水线函数。为此,只需将函数实现替换为以下代码:
create or replace function get_last_data_pipe
return t_rowlist pipelined
as
v_table varchar2(30);
v_row t_row;
v_cursor sys_refcursor;
begin
select table_name into v_table from (
select * from user_tables where table_name like 'T%'
order by lpad(substr(table_name,2),40,'0') desc
)
where rownum = 1;
open v_cursor for 'select t_row(n) from '|| v_table;
loop
fetch v_cursor into v_row;
exit when v_cursor%notfound;
pipe row(v_row);
end loop;
close v_cursor;
return;
end;
链接以测试 SQLFiddle。