如何写Alter Table并添加新列?

Hem*_*yal -2 database sql-server oracle

我有一个表有3列A,B,C的表也有行.A列是主键.

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

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

E列和F列为NULL.

请帮我创建alter table语句.

APC*_*APC 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>
Run Code Online (Sandbox Code Playgroud)

所以,第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>
Run Code Online (Sandbox Code Playgroud)

现在我们可以强制列D:

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

Table altered.

SQL>
Run Code Online (Sandbox Code Playgroud)

最后,我们可以将主键列从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>
Run Code Online (Sandbox Code Playgroud)

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