Thursday, November 8, 2012

Insert Records from one table to another table

Before records insertion from one table to another table we must need to aware of these steps

1. New table need to be create with data.
2. Table is exists but we need to copy all records.
3. Table is exists and we wanted to copy particular records on existing table.

How to copy records for all the above steps.

Note : - Consider we have tblSource with all records Ex:-
Create table tblSource(Id int Primary Key,Name varchar(50), Address varchar(100),Created datetime default getdate())
Insert into tblSource(Id,Name,Address) values (1,'Murli','Mumbai-Sanpada')
Insert into tblSource(Id,Name,Address) values (2,'Deepak','Mumbai-Vasai')
Insert into tblSource(Id,Name,Address) values (3,'Ajit','Mumbai-Thane')


1. New table need to be create with data when target table is not exists.
       Select * Into tblIntoSource from tblSource


2. Target table exists and i wanted to copy all the records from source table.
       Insert tblSourceCopy Select * from tblSource


3. Target table exists and i wanted to copy particular records on it... i have two option to do this.
  A. Using Into Command
       Insert into tblDest(Id,Name) Select Id,Name from tblSource

  B. Using Direct Insert Command
       Insert tblSourceCopy1(Id,Name) Select Id,Name from tblSource

 

No comments:

Post a Comment