2

Can anyone offered syntax for a sql query that takes an already created table and inserts some of the data into a new table with a new id(primary key)? So far I tried this

SELECT ((ID INT IDENTITY(1,1) PRIMARY KEY), column1, column2, column3)
INTO table_name
FROM table_name 

I keep coming up with a syntax error.

2
  • Just for understanding: Why don't you just copy the 'from'-table and change the primary key afterwards with an "alter-table" statement? Commented May 3, 2012 at 15:06
  • You can't insert a column declaration into a table row. And your example is selecting into table_name from table_name - you might want to update your example to make it clearer that you (do you?) mean INTO target_table FROM source_table. Commented May 3, 2012 at 15:12

5 Answers 5

4
SELECT column1, column2, column3
INTO table_name_new
FROM table_name_old

use like this

Sign up to request clarification or add additional context in comments.

Comments

3
INSERT INTO newtable (column1, column2, column3)
SELECT (column1, column2, column3) 
FROM table_name  

Comments

2
INSERT INTO new_table
(Column1, Column2 . . . )

SELECT Column1, Column2 FROM old_table

Don't include the identity column (the primary key with the auto-generated numbers) in the insert list.

Comments

2

Just make it like below, Aa new id will be automatically created while inserting the record

insert into table1 (col1,col2,col3) select col1,col2,col3 from table2;

Comments

1

According to the documentation on MSDN, the IDENTITY property will transfer through with a SELECT INTO clause, but constraints will not. That means you can create a new table with an IDENTITY column if you include the original IDENTITY column from your source table, but the column in the new table won't be a primary key.

The sane way to do this is to use ALTER TABLE after the table is created, as @Kai has suggested.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.