Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 表创建后的交换列顺序_Sql_Oracle - Fatal编程技术网

Sql 表创建后的交换列顺序

Sql 表创建后的交换列顺序,sql,oracle,Sql,Oracle,我创建了一个包含4列的表。我需要改变桌子的结构。我需要永久交换第4列和第2列的位置。这在Oracle中可能吗?不可能。看 Oracle只允许将列添加到现有列的末尾 桌子 因此,您必须删除并重新创建表。您可以运行如下脚本: 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

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

不可能。看

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


因此,您必须删除并重新创建表。

您可以运行如下脚本:

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

<>你需要考虑索引和存储问题。

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

交换列col1和col2
假设col1是
int
,col2是
varchar2(20)


如果表列是相同的数据类型,只需重命名它们。如果没有,则更改-参见Sean和Egor示例

重命名:


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

需要对列重新排序吗?你可以在陈述中以任何顺序选择它们,也可以以任何顺序插入它们。我同意所有询问“为什么”的评论和回答,因为没有逻辑理由更改列顺序。然而,在12c中有一个技巧可以做到这一点:我在一次采访中被问到这个问题。根据采访者的说法,这是可能的。
-- 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