SQL Server SELECT into existing table

Daniel picture Daniel · Nov 4, 2010 · Viewed 504.3k times · Source

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?

Answer

OMG Ponies picture OMG Ponies · Nov 4, 2010

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