Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server SELECT into existing table

I am trying to select some fields from one table and insert them into an existing table from a stored procedure. Here is what I am trying:

SELECT col1, col2 INTO dbo.TableTwo  FROM dbo.TableOne  WHERE col3 LIKE @search_key 

I think SELECT ... INTO ... is for temporary tables which is why I get an error that dbo.TableTwo already exists.

How can I insert multiple rows from dbo.TableOne into dbo.TableTwo?

like image 306
Daniel Avatar asked Nov 04 '10 21:11

Daniel


People also ask

What is select into existing table?

For Existing Table - INSERT INTO SELECT. This method is used when the table is already created in the database earlier and the data is to be inserted into this table from another table. If columns listed in insert clause and select clause are same, they are not required to list them.

How will you insert data from one table to another existing table in SQL Server?

The SQL INSERT INTO SELECT Statement The INSERT INTO SELECT statement copies data from one table and inserts it into another table. The INSERT INTO SELECT statement requires that the data types in source and target tables match. Note: The existing records in the target table are unaffected.

How do I insert a select query result into a table?

From the Query Designer menu, point to Change Type, and then click Insert Results. In the Choose Target Table for Insert Results Dialog Box, select the table to copy rows to (the destination table).


1 Answers

SELECT ... INTO ... only works if the table specified in the INTO clause does not exist - otherwise, you have to use:

INSERT INTO dbo.TABLETWO SELECT col1, col2   FROM dbo.TABLEONE  WHERE col3 LIKE @search_key 

This assumes there's only two columns in dbo.TABLETWO - you need to specify the columns otherwise:

INSERT INTO dbo.TABLETWO   (col1, col2) SELECT col1, col2   FROM dbo.TABLEONE  WHERE col3 LIKE @search_key 
like image 195
OMG Ponies Avatar answered Oct 07 '22 04:10

OMG Ponies