将表附加到现有表:SQL Server
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23316862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append table to an existing one: SQL Server
提问by npereira
I have a table A
with two columns that I want to append to another table B
, how can I do that? They have the exact same rows. Software is SQL Server 2012
.
我有一个A
包含两列的表,我想将其附加到另一个表中B
,我该怎么做?它们具有完全相同的行。软件是SQL Server 2012
.
EDIT (attempted code from comment):
编辑(来自评论的尝试代码):
INSERT INTO B_table([Column 0], [Column 1])
SELECT [Column 0], [Column 1]
FROM [dbo].[A] ;
采纳答案by Gordon Linoff
The basic form is:
基本形式是:
insert into tableB(col1, col2)
select col1, col2
from tableA;
This may not work if, for instance, you have a unique constraint on the columns and the insert
violates this constraint.
例如,如果您对列有唯一约束并且insert
违反了此约束,则这可能不起作用。
This assumes that you actually want to add the rows to the table. If you just want to see the results together:
这假设您确实想要将行添加到表中。如果您只想一起查看结果:
select col1, col2 from tableB union all
select col1, col2 from tableA;
EDIT:
编辑:
The goal seems to be to add columns one tableB
. You can do this by adding the columns and then updating the values:
目标似乎是添加第一列tableB
。您可以通过添加列然后更新值来做到这一点:
alter table tableB add col1 . . . ;
alter table tableB add col2 . . . ;
The . . .
is the definition of the column.
该. . .
是列的定义。
Then do:
然后做:
update b
set col1 = a.col1, col2 = b.col2
from tableb b join
tablea a
on b.joinkey = a.joinkey;
If you don't have a column for joining, then you have a problem. Tables in SQL are inherently unordered, so there is no way to assign values from a particular row of A
to a particular row of B
.
如果您没有用于加入的列,那么您就有问题了。SQL 中的表本质上是无序的,因此无法将值从 的特定行分配A
到 的特定行B
。
回答by Chong Lip Phang
Try this:
尝试这个:
INSERT INTO tbl1 SELECT * FROM tbl2;
回答by Charles Bretana
If the new table does not exist yet, you have to create it first, or use the form:
如果新表尚不存在,则必须先创建它,或者使用以下形式:
Select [Column list] Into [NewTableName] From [oldTableName]
,
Select [Column list] Into [NewTableName] From [oldTableName]
,
as in
如
Select col1, col2
Into NewTable
From OldTable