SQL: Insert all records from one table to another table without specific the columns SQL: Insert all records from one table to another table without specific the columns sql-server sql-server

SQL: Insert all records from one table to another table without specific the columns


You should not ever want to do this. Select * should not be used as the basis for an insert as the columns may get moved around and break your insert (or worse not break your insert but mess up your data. Suppose someone adds a column to the table in the select but not the other table, you code will break. Or suppose someone, for reasons that surpass understanding but frequently happen, decides to do a drop and recreate on a table and move the columns around to a different order. Now your last_name is is the place first_name was in originally and select * will put it in the wrong column in the other table. It is an extremely poor practice to fail to specify columns and the specific mapping of one column to the column you want in the table you are interested in.

Right now you may have several problems, first the two structures don't match directly or second the table being inserted to has an identity column and so even though the insertable columns are a direct match, the table being inserted to has one more column than the other and by not specifying the database assumes you are going to try to insert to that column. Or you might have the same number of columns but one is an identity and thus can't be inserted into (although I think that would be a different error message).


Per this other post: Insert all values of a..., you can do the following:

INSERT INTO new_table (Foo, Bar, Fizz, Buzz)SELECT Foo, Bar, Fizz, BuzzFROM initial_table

It's important to specify the column names as indicated by the other answers.


Use this

SELECT *INTO new_table_nameFROM current_table_name