Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically match columns in INSERT INTO ... SELECT ... FROM

Tags:

SQL Server question. When doing

INSERT INTO T1 SELECT (C1, C2) FROM T2 

I don't want to specify column names of T1 because they are the same as in T2

Is it possible to do so?

Currently I'm getting error

Msg 213, Level 16, State 1, Line 1

Column name or number of supplied values does not match table definition.

like image 701
Konstantin Spirin Avatar asked Nov 24 '09 03:11

Konstantin Spirin


People also ask

Can we use insert and select together?

You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.

Can you insert data in selected columns using insert into statement?

You can still insert records into the destination table with specifying column names in the INSERT INTO SELECT statement. We should have an appropriate data type to insert data. You cannot insert a varchar column data into an INT column.

Which is faster select into or insert into?

INTO' creates the destination table, it exclusively owns that table and is quicker compared to the 'INSERT … SELECT'. Because the 'INSERT … SELECT' inserts data into an existing table, it is slower and requires more resources due to the higher number of logical reads and greater transaction log usage.

What is the difference between insert into to select?

INSERT INTO SELECT statement in SQL Server is used to copy data from the source table and insert it into the destination table. The SELECT INTO statement in SQL Server is used to copy data from one (source) table to a new table. INSERT INTO SELECT requires the destination table to be pre-defined.


1 Answers

Always use explicit columns both in the INSERT and in the SELECT projection. Even if you don't want to, you should:

INSERT INTO T1 (C1, c2) SELECT C1, C2 FROM T2 
like image 168
Remus Rusanu Avatar answered Sep 21 '22 00:09

Remus Rusanu