2013-03-14 26 views
-4

我創建了一個包含4列的表。我需要改變表格的結構。我需要永久性地改變第4列和第2列的位置。這在Oracle中可能嗎?創建表後創建表的列順序

+6

什麼是需要重新排列列?您可以在報表中以任意順序選擇它們,也可以按任意順序插入它們。 – Jeff 2013-03-14 14:26:52

+0

我同意詢問「爲什麼」的所有評論和答案,因爲沒有理由改變列順序。然而,在12c中有一個技巧:http://tkyte.blogspot.com.au/2013/07/12c-silly-little-trick-with-invisibility.html – 2013-07-03 00:53:10

回答

5

不可能。見this

Oracle只允許將列添加到現有 表的末尾。

因此,您必須刪除並重新創建表格。

+0

我在採訪中被問到這個問題。根據面試官的說法,這是可能的。 – user2170216 2013-03-14 14:46:18

3

您可以運行類似下面的腳本:

CREATE TABLE TMP_TBL as SELECT * FROM TBL_ORIG; 
ALTER TABLE TBL_ORIG ADD COLUMN COL3; 
DROP TABLE TBL_ORIG; 
CREATE TABLE TBL_ORIG AS SELECT COL1, COL3, COL2 FROM TMP_TBL; 
DROP TABLE TMP_TBL 

你需要考慮的索引以及存儲的擔憂。

2

爲什麼在這個世界上這是必要的?列順序在SQL中沒有任何意義。

2

列COL1的交換和COL2
假定COL1是int和COL2是varchar2(20)

-- drop all indexes and constraints concerning col1 and col2 
alter table your_table add temp_col int;   -- type of col1 
update your_table set col1 = null, temp_col = col1; 
alter table your_table modify col1 varchar2(20); -- type of col2 
update your_table set col2 = null, col1 = col2; 
alter table your_table modify col2 int;   -- type of col1 
update your_table set col2 = temp_col; 
alter table your_table drop column temp_col; 
alter table your_table rename column col1 to temp_col; 
alter table your_table rename column col2 to col1; 
alter table your_table rename column temp_col to col1; 
-- recreate indexes and constraints