正如你說你調用一個過程,從視圖中創建一個表。因此,我假設您已經在使用動態SQL(原生動態SQL,也稱爲EXECUTE IMMEDIATE
語句或DBMS_SQL
包)來執行DDL語句。然後,您可以使用Oracle字典視圖(例如USER_VIEWS和USER_TAB_COLUMNS)生成更復雜的CREATE TABLE AS
語句,以獲取有關列的類型,長度,比例以及編寫正確CAST調用所需的任何其他信息。
髒例子如下:
create or replace view v
as
select decode(dummy, 'Y', '123') s
, 1 n
, 2.2 f
, cast (1.1 as number(5,3)) fs
from dual
/
set serveroutput on
declare
l_query varchar2(32767) := 'create table t as select <column list> from v';
l_type varchar2(100);
begin
for tc in (
select * from user_tab_columns
where table_name = 'V'
order by column_id
) loop
l_type := tc.data_type;
l_type := l_type ||
case tc.data_type
when 'NUMBER' then
case when tc.data_precision is not null then '(' || tc.data_precision || case when tc.data_scale is not null then ','||tc.data_scale end || ')' end
when 'VARCHAR2' then
'(' || tc.char_length || ' ' || case tc.char_used when 'C' then 'char' else 'byte' end || ')'
end;
l_query := replace(l_query, '<column list>', 'cast("'||tc.column_name||'" as '|| l_type ||') "'||tc.column_name||'" ,<column list>');
end loop;
l_query := replace(l_query, ',<column list>');
dbms_output.put_line(l_query);
end;
/
結果:
view V created.
anonymous block completed
create table t as select cast("S" as VARCHAR2(3 char)),cast("N" as NUMBER),cast("F" as NUMBER),cast("FS" as NUMBER(5,3)) from v
好運。
爲什麼不使用物化視圖?你完全需要這些表格嗎? – tbone
視圖是簡單過濾從單個表中選擇的,還是將函數應用於值? –