Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT INTO SELECT * for SQL Server, Not possible, Am I correct?

Using SQL Server 2008 R2

Apparently one can do

INSERT INTO Table1 SELECT * FROM Table1 where Id=1234

see: W3Schools

But in SQL Server this does not work. Am I correct in thinking that SQL Server does not support the above INSERT statement, and needs to specify the columns specifically.

Thanks.

EDIT

So incomplete SQL above, now corrected

like image 906
SamJolly Avatar asked Aug 27 '26 23:08

SamJolly


2 Answers

You missed the name of the table you want to insert into

insert into destination_table
select * from source_table

Of course this works only for tables with equal columns. If you only want to insert specific columns then you need to specify them too

insert into destination_table (col1, col2)
select col7, col3 from source_table
like image 157
juergen d Avatar answered Aug 30 '26 20:08

juergen d


If you're simply trying to copy a row from a table that has a primary key (IDENTITY column), then you can't use the following syntax:

INSERT INTO Table1 SELECT * FROM Table1 where Id=1234

This would violate the unique primary key values as it would try to insert a duplicate IDENTITY.

Instead, select all columns except the IDENTITY, assuming with this schema:

Table1
------
ID
Col1
Col2
Col3

You would do this and the IDENTITY would auto increment for you:

INSERT INTO Table1 (Col1, Col2, Col3)
SELECT Col1, Col2, Col3
FROM Table1 
WHERE Id=1234
like image 31
Tanner Avatar answered Aug 30 '26 21:08

Tanner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!