如何写Alter Table并添加新列?

时间:2011-07-19 11:57:18

标签: sql-server database oracle

我有一个包含3列A,B,C的表,它也有行。 A列是主键。

现在根据新要求,我需要添加新的D,E和F列。

此外,我还需要从A列中删除以前的主键,并为D列添加新的主键。

E列和F列为NULL。

请帮我创建alter table语句。

1 个答案:

答案 0 :(得分:11)

您需要的是一个多步骤的过程。添加列,删除现有主键约束,最后添加新约束。

这里最困难的是添加D列。因为您希望它是新的主键,所以它必须是NOT NULL。如果您的表有现有数据,则需要处理此错误:

SQL> alter table your_table
  2     add ( d number not null
  3           , e date
  4           , f number )
  5  /
alter table your_table
            *
ERROR at line 1:
ORA-01758: table must be empty to add mandatory (NOT NULL) column


SQL>

所以,第1步是添加D列可选的新列;然后使用任何键值填充它:

SQL> alter table your_table
  2     add ( d number
  3           , e date
  4           , f number )
  5  /

Table altered.

SQL> update your_table
  2      set d = rownum
  3  /

1 row updated.

SQL>

现在我们可以强制列D:

SQL> alter table your_table
  2     modify d not null
  3  /

Table altered.

SQL>

最后,我们可以将主键列从A更改为D:

SQL> alter table your_table
  2      drop primary key
  3  /

Table altered.

SQL> alter table your_table
  2     add constraint yt_pk primary key (d)
  3  /

Table altered.

SQL>

对于某些更改,我们要添加具有默认值的列。在这种情况下,可以一步完成:

alter table your_table
add new_col varchar2(1) default 'N' not null;

在Oracle的后续版本中,实际上非常有效地使用相同的值填充新列,这比上面概述的多步骤方法快得多。


如果不清楚上面的语法是Oracle。我希望SQL Server会有类似的东西。

相关问题