通过从另一个表中选择列来将列附加到表

时间:2013-01-25 05:21:55

标签: sql

Alter Table table2 add ( select column1, column2, column3, column4 from table1 );

我需要通过选择另一个表的列来在现有表中追加列。

我收到错误!期待可能的解决方案

1 个答案:

答案 0 :(得分:0)

首先,要向表中添加四个新列,请使用以下语法:

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

接下来,要将table1中的数据作为全新记录插入此表,您将使用以下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
相关问题