Oracle 中没有这样做的“选项”;您也许可以找到允许您这样做的客户,因为这是通常在客户中完成的工作;我不知道一个。
要扩展tbone 的答案,您将不得不动态地执行此操作。这并不意味着您必须列出每一列。您将使用数据字典,特别是all_tab_columns或user_tab_columns
创建您的查询。使用您想要的确切定义创建视图会更容易,以便您可以根据需要重新使用它。
目的是利用存在的列作为字符串存储在表中这一事实,以便创建查询以使用该列。由于列名和表名存储为字符串,您可以使用字符串聚合技术轻松创建查询或 DDL 语句,然后您可以手动或动态执行这些语句。
如果您使用的是 Oracle 11g 第 2 版,该listagg
功能可以帮助您:
select 'create or replace view my_view as
select '
|| listagg( table_name || '.' || column_name
|| ' as '
|| substr(table_name,1,1) || '_'
|| column_name, ', ')
within group
( order by case when table_name = 'FOO' then 0 else 1 end
, column_id
)
|| ' from foo f
join bar b
on f.id = b.foo_id'
from user_tab_columns
where table_name in ('FOO','BAR')
;
假设这个表结构:
create table foo ( id number, a number, b number, c number);
create table bar ( foo_id number, a number, b number, c number);
此单个查询产生以下结果:
create or replace view my_view as
select FOO.ID as F_ID, FOO.A as F_A, FOO.B as F_B, FOO.C as F_C
, BAR.FOO_ID as B_FOO_ID, BAR.A as B_A, BAR.B as B_B, BAR.C as B_C
from foo f
join bar b on f.id = b.foo_id
这是一个SQL Fiddle来证明它。
在您不使用 11.2 时,您可以使用由 Tom Kyte 创建的未记录函数wm_concat
或用户定义函数获得完全相同的结果。stragg
Oracle Base 有一篇关于字符串聚合技术的文章,并且有很多关于 Stack Overflow 的帖子。
作为一个小附录,您实际上可以通过对上述查询进行小的更改来创建您正在寻找的内容。您可以使用带引号的标识符来创建TABLE_NAME.COLUMN_NAME
格式中的列。您必须引用它,因为.
它不是 Oracle 中对象名称的有效字符。这样做的好处是你得到你想要的。缺点是如果你不使用select * from ...
;查询创建的视图是一个巨大的痛苦。选择命名列将要求它们被引用。
select 'create or replace view my_view as
select '
|| listagg( table_name || '.' || column_name
|| ' as '
|| '"' || table_name || '.'
|| column_name || '"', ', ')
within group
( order by case when table_name = 'FOO' then 0 else 1 end
, column_id
)
|| ' from foo f
join bar b
on f.id = b.foo_id'
from user_tab_columns
where table_name in ('FOO','BAR')
;
此查询返回:
create or replace view my_view as
select FOO.ID as "FOO.ID", FOO.A as "FOO.A", FOO.B as "FOO.B", FOO.C as "FOO.C"
, BAR.FOO_ID as "BAR.FOO_ID", BAR.A as "BAR.A"
, BAR.B as "BAR.B", BAR.C as "BAR.C"
from foo f
join bar b on f.id = b.foo_id