正如你所说,你调用一个过程来从视图中创建一个表。所以我假设您已经在使用动态 SQL(Native Dynamic SQL aka EXECUTE IMMEDIATE
statement or DBMS_SQL
package)来执行 DDL 语句。CREATE TABLE AS
然后,您可以使用 Oracle 字典视图(如USER_VIEWS和USER_TAB_COLUMNS )生成更复杂的语句,以获取有关列类型、长度、比例以及编写正确 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
祝你好运。