2011-07-19 309 views
-2

我有一個表有3列A,B,C也有行。列A是主鍵。如何編寫Alter Table並添加新列?

現在按照新規定,我需要添加新列d,E和F

此外,我需要刪除從A列中的前一個主鍵,添加一個新的主鍵列D.

列E和F爲NULL。

請幫我創建alter table語句。

+4

-1在發佈問題前搜索並閱讀基本文檔。今天下載文檔非常簡單,應該成爲首先使用新技術的文檔之一。 –

回答

11

你需要的是一個多步驟的過程。添加列,刪除現有的主鍵約束,並最終添加一個新的。

這裏最困難的事情就是添加D列。因爲你希望它成爲新的主鍵,它必須是非空的。如果您的表已經存在的數據,你將需要處理此錯誤:

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> 

所以,第一步是增加與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> 

如果不清楚上面的語法是Oracle。我預計SQL Server將會類似。

+0

謝謝! :)它爲我工作。 – sedran