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
?
There are two different ways to implement inserting data from one table to another 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. It is good practice to always list them for readability and scalability purpose.
For Non-Existing Table - SELECT INTO
This method is used when the table is not created earlier and needs to be created when data from one table is to be inserted into the newly created table from another table. The new table is created with the same data types as selected columns.
Ref 1 2
SELECT ... INTO ...
only works if the table specified in the INTO clause does not exist - otherwise, you have to use:This assumes there's only two columns in dbo.TABLETWO - you need to specify the columns otherwise:
It would work as given below :
If you have used
select * into tablename from other tablenames
already, next time, to append, you sayselect * into existing table tablename from other tablenames