SQL Server – Insert Data from one Table to another Table

Insert Data from one Table to another Table

We often come across situations when we want to copy data from one table into another table. There are two ways to do so:

1.         INSERT / SELECT

It is used to insert the result set of select statement on a table into another table. The only consideration that has to be taken care of is – data types of the corresponding column must be compatible.

— Inserting records into Customer table form

— Europe_Customer table

INSERT INTO Customer (CustID, LastName, FirstName)

SELECT CID, LName, Fname FROM Europe_Customer;

We can also use WHERE clause to filter the data

— Inserting records into Customer table form

— Europe_Customer table Where city is London

INSERT INTO Customer (CustID, LastName, FirstName)

SELECT CID, LName, Fname

FROM Europe_Customer

WHERE City=‘London’

2.         SELECT INTO

It creates a new table and the result set of a select statement is use to populate this new table whose name is specified in the statement. We can also use WHERE clause to filter the records need for insertion.

— A new table CustomerAddress is created with

— CustID and Address columns and data is copied from Customer Table

SELECT CustID, Address

INTO CustomerAddress

FROM Customer

WHERE City=‘London’

Good Luck!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: