在Oracle中沒有「選項」來執行此操作;你可能能夠找到一個客戶端,允許你這樣做,因爲這是通常在客戶端完成的工作;我不知道一個。
要擴大tbone's answer你將不得不動態做到這一點。這不意味着你必須列出每一列。您將使用data dictionary,特別是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有一篇關於string aggregation techniques的文章,並且在Stack Overflow上有很多帖子。
作爲一個小附錄,您可以通過對上述查詢的小改動實際創建您正在查找的內容。您可以使用quoted identifier創建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')
;
This query returns:
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
İ'm在PL/SQL無法勝任的,但也許你可以嘗試加入他們之前,重命名錶中的列。 – bonsvr
您如何導出數據?也許這個邏輯屬於那個導出工具,而不是單個的語句? –