创建表后交换列的顺序

时间:2013-03-14 14:25:31

标签: sql oracle

我创建了一个包含4列的表。我需要改变表的结构。我需要永久地交换第4和第2列的位置。这可能在Oracle吗?

5 个答案:

答案 0 :(得分:5)

不可能。请参阅this

  

Oracle只允许将列添加到现有的末尾   表

所以你必须删除并重新创建表格。

答案 1 :(得分: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 :(得分:2)

为什么这个世界是必要的?列顺序在SQL中没有任何意义。

答案 3 :(得分: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

答案 4 :(得分:2)

如果表列是相同的数据类型,则只需重命名表列。如果没有,那么Alter - 见Sean和Egor的例子。

重命名: http://docs.oracle.com/cd/E11882_01/server.112/e25494/tables006.htm#ADMIN11662

在采访中他们正在寻找肖恩的答案。仅供参考......

相关问题