Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL Insert into table without having to specify every column

In our db there is a table that has a little over 80 columns. It has a primary key and Identity insert is turned on. I'm looking for a way to insert into this table every column EXCEPT the primary key column from an identical table in a different DB.

Is this possible?

like image 229
Eric Avatar asked Mar 05 '12 20:03

Eric


People also ask

Can you insert values into tables without writing column names?

There are two ways of using INSERT INTO statement for inserting rows: Only values: First method is to specify only the value of data to be inserted without the column names. INSERT INTO table_name VALUES (value1, value2, value3,…); table_name: name of the table.

Does SQL insert need all columns?

In order to insert default values to the columns, you just need exclude the default columns from the insert list with a SQL insert into statement.

When inserting data in a table do you always have to specify a list of all column names you are inserting values for no yes?

As long as you have the right number of columns in your INSERT statement, and as long as all the values except KEYBOARD are some numeric data type, and as long as you have suitable permissions, this should work. INSERT INTO INVOICE VALUES( 1,1,'KEYBOARD',1,15,5,75);

Is it possible to only insert data in specific columns?

It is also possible to only insert data in specific columns.


2 Answers

You can do this quite easily actually:

-- Select everything into temp table Select * Into      #tmpBigTable     From [YourBigTable]  -- Drop the Primary Key Column from the temp table   Alter Table #tmpBigTable Drop Column [PrimaryKeyColumn]  -- Insert that into your other big table Insert Into [YourOtherBigTable]     Select * From #tmpBigTable  -- Drop the temp table you created Drop Table #tmpBigTable 

Provided you have Identity Insert On in "YourOtherBigTable" and columns are absolutely identical you will be okay.

like image 190
Ta01 Avatar answered Oct 06 '22 00:10

Ta01


You could query Information_Schema to get a list of all the columns and programatically generate the column names for your query. If you're doing this all in t-sql it would be cumbersome, but it could be done. If you're using some other client language, like C# to do the operation, it would be a little less cumbersome.

like image 41
Kibbee Avatar answered Oct 06 '22 00:10

Kibbee