سؤال

Say table1 and table2 already exist, is there any difference between these queries

query1 :-

select * into table1 from table2 where 1=1

query2: -

insert into table1 select * from table2
هل كانت مفيدة؟

المحلول

The select * into table1 from table2 where 1=1 creates table1 and inserts the values of table2 in them. So, if the table is already created that statement would give an error.

The insert into table1 select * from table2 only inserts the values of table2 in table1.

نصائح أخرى

The first one (SELECT INTO) will create and populate a new table the second (INSERT... SELECT) inserts to an existing table.

In versions of SQL Server prior to 2008 the first one could be minimally logged and the second one not but this is no longer true.

select * into table1 from table2 where 1=1

The query above requires that the table DOES NOT exist. You do not need to specify columns as all columns are created as they are retrieved from the source table.

insert into table1 select * from table2 

For the above query, you need an EXISTING table1. The columns in both tables should also be in exactly the same order, otherwise you need to provide a column list for both tables.

In below query, table1 will be created or an error will be thrown if it already exists

select * into table1 from table2 where 1=1

In below query, the table table1 must exist before running the command

insert into table1 select * from table2
INSERT INTO TABLE_A SELECT * FROM TABLE_B

Is a commonly used sentence, which is used to insert values of a table into another table. Selected columns can also be inserted using this.

SELECT * INTO TABLE_A FROM TABLE_B

Will create a new TABLE_A populated with values of TABLE_B

a) select * into table1 from table2 where 1=1 -If table1 and table2 already exist, you will get below error when you execute the query. "Msg 2714, Level 16, State 6, Line 1 There is already an object named 'table1' in the database"

b) insert into table1 select * from table2 -If table1 is duplicate of table2 ,then this query consider common insert statement Exp: select * into table1 from table2 where 1=0 However bare in mind, you will accumulate duplicate data each time you execute the query.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top