是否有任何设置或方法可以让 Oracle 返回 <table>.<column>
中的结果格式?例如:
查询:
SELECT *
FROM foo f
INNER JOIN bar b
ON b.foo_id = f.id
期望的结果:
F.ID F.BLAH B.ID B.FOO_ID B.BLAH
--------------------------------------------------------
1 blah 7 1 blah
2 blah 8 2 blah
3 blah 9 2 blah
显而易见的解决方案是为每列单独设置别名 SELECT f.id AS F_ID, ...
;但是,我需要导出一些非常大的旧表(300 多列),因此使用此方法会导致查询庞大且不切实际。
最佳答案
Oracle 中没有“选项”可以执行此操作;您也许能够找到允许您这样做的客户端,因为这是通常在客户端完成的工作;我不知道有一个。
扩展 tbone's answer你必须动态地执行此操作。这并不意味着您必须列出每一列。您可以使用 data dictionary ,具体来说all_tab_columns或 user_tab_columns
创建您的查询。创建具有您想要的确切定义的 View 会更容易,以便您可以根据需要重复使用它。
目的是利用列的存在作为字符串存储在表中的事实,以便创建查询来使用该列。由于列名和表名存储为字符串,因此您可以使用字符串聚合技术轻松创建查询或 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,则可以使用未记录的函数 wm_concat
获得完全相同的结果。或用户定义函数stragg
,由汤姆·凯特创建。 Oracle Base 有一篇关于 string aggregation techniques 的文章Stack Overflow 上有很多帖子。
作为一个小附录,您实际上可以通过对上述查询进行少量更改来创建您正在寻找的内容。您可以使用 quoted identifier以 TABLE_NAME.COLUMN_NAME
格式创建列。您必须将其引用为。
不是Oracle中对象名称的有效字符。这样做的好处是你得到的正是你想要的。缺点是,如果不使用 select * from ...
,查询创建的 View 会非常痛苦;选择命名列将要求它们被引用。
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
关于oracle - 以 table.column 格式返回 Oracle 列名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12230650/