Follow sqlserver-dba.com

Subscribe to RSS feed  Follow @jackvamvas - Twitter

*Use the Comments section for questions

SQLServer-DBA.com Links

Dba_db2_button

dba-ninja.com

SQL Server DBA Jobs

INSERT SELECT into existing table

08 May,2015 by Tom Collins

Question: How can I INSERT  into an existing  table  using a SELECT statement from an existing table?

I don’t want to create  a new table , just simply INSERT  into an existing table

Answer:   To INSERT data  from an existing table into an existing table use the INSERT INTO  .. SELECT method. This method will  take a recordset from an existing  table and inserts into another existing table.

INSERT INTO myTable(col1,col2)

SELECT col1,col2 FROM myTableexisting

A common misunderstanding is to use the following pattern, which creates a new table.

SELECT * INTo myNewTable FROM myOLDTable

USE SQL_TOOLS
go
CREATE TABLE myTest 
(myID INT,
myvalue VARCHAR(100)
)
CREATE TABLE myTest2 
(myID INT,
myvalue VARCHAR(100)
)

GO
--insert source data into source table
INSERT INTO myTest
SELECT 1,'myvalue1'
UNION
SELECT 2, 'myalue2'
GO
--copy source data into a another table
INSERT INTO myTest2 (myID,myValue)
SELECT myID,myValue FROM myTest WHERE myID = 1

SELECT * FROM myTest2

DROP TABLE myTest
DROP TABLE myTest2

Read More on T-SQL

SQL Server - Bulk Insert CSV into a SQL Server table - SQL

 

 


Author: Tom Collins (http://www.sqlserver-dba.com)


Share:

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment on INSERT SELECT into existing table


sqlserver-dba.com | SQL Server Performance Tuning | SQL Server DBA:Everything | FAQ | Contact|Copyright & Disclaimer