2013-01-25 40 views
0
Alter Table table2 add (select column1, column2, column3, column4 from table1); 

我需要通過選擇另一個表的列來追加現有表中的列。通過從另一個表中選擇列將列附加到表中

我收到錯誤!展望未來一個可能的解決方案

+2

您想做什麼?基於另一個表中的值將列動態添加到表中?你能舉一個你的數據的例子,你想要實現什麼? –

+0

我只是試圖將來自另一個表的值添加到我的表中的4列。有沒有條件.. – Yoshi

+0

對不起,這仍然不清楚。你能舉一個你的數據和結果的例子嗎? –

回答

0

第一,4個新列添加到表中使用的語法如下:

ALTER TABLE Table2 
      ADD column1 <datatype> <allow null>, 
       column2 <datatype> <allow null>, 
       column3 <datatype> <allow null>, 
       column4 <datatype> <allow null> 

哪裏<datatype>是一個數據,你會被添加到列和<allow null>類型是NULL如果您希望允許空值是列,並且NOT NULL如果您不希望在列中允許空值。

例如添加一個類型NCHAR的四列的大小爲10,允許空值,你會做以下幾點:

ALTER TABLE Table2 
      ADD column1 [nchar](10) NULL, 
       column2 [nchar](10) NULL, 
       column3 [nchar](10) NULL, 
       column4 [nchar](10) NULL 

接下來,從表1中插入您的數據到這個表作爲品牌的新紀錄你可以使用下面的SQL:

insert into  table2 (column1, column2, column3, column4) 
       select column1, column2, column3, column4 
       from table1 

注:如果任何在你的表被設置爲NOT NULL並沒有原來的列有一個默認值,這將失敗,你將不得不爲這些列設定值以及。您可以通過使用類似於爲不允許NULL值的列設置特定值的命令來執行此操作:

insert into  table2 (existingColumn, column1, column2, column3, column4) 
       select 'value to insert', column1, column2, column3, column4 
       from table1 
相關問題