SQL Server'select * into'与'insert into ..select *

时间:2011-12-19 11:27:16

标签: sql-server select-into

table1table2已经存在,这些查询之间是否存在差异

query1: -

select * into table1 from table2 where 1=1

query2: -

insert into table1 select * from table2

5 个答案:

答案 0 :(得分:42)

select * into table1 from table2 where 1=1创建table1并在其中插入table2的值。因此,如果表已经创建,那么该语句会产生错误。

insert into table1 select * from table2仅在table1中插入table2的值。

答案 1 :(得分:8)

第一个(SELECT INTO)将创建并填充新表,第二个(INSERT... SELECT)插入到现有表中。

在2008年之前的SQL Server版本中,第一个版本可以最少记录,第二个版本可以只是this is no longer true

答案 2 :(得分:5)

select * into table1 from table2 where 1=1

上述查询要求表格不存在。您不需要指定列,因为从源表中检索它们时会创建所有列。

insert into table1 select * from table2 

对于上述查询,您需要一个EXISTING table1。 两个表中的列也应该完全相同,否则您需要为两个表提供列列表。

答案 3 :(得分:1)

INSERT INTO TABLE_A SELECT * FROM TABLE_B

是一个常用的句子,用于将表的值插入另一个表中。也可以使用此插入选定的列。

SELECT * INTO TABLE_A FROM TABLE_B

将创建一个填充了TABLE_B

值的新TABLE_A

答案 4 :(得分:0)

a)从表2中的表1中选择*,其中1 = 1 -如果table1和table2已经存在,则执行查询时将出现以下错误。 “消息2714,第16层,状态6,第1行 数据库中已经有一个名为“ table1”的对象。

b)插入表1中,从表2中选择* -如果table1是table2的重复项,则此查询考虑共同的insert语句 Exp:从表2中的表1中选择*,其中1 = 0 不管您在想什么,每次执行查询时,您都会积累重复数据。