Tuesday, December 24, 2013

Copy a table into new table with/without data conditionally / unconditionally - SQL Server

1. Copy only the structure of an existing table into new table:

SELECT * INTO [DBName]. dbo.tblNonExistingTable FROM [DBName].dbo.tblExistingTable WHERE 1=2

The above query will copy the structure of  an existing table(tblExistingTable ) into the new table(tblNonExistingTable).


2. Copy the structure plus all the data of an existing table into new table:

SELECT * INTO [DBName]. dbo.tblNonExistingTable FROM [DBName].dbo.tblExistingTable

The above query will copy the structure of  an existing table(tblExistingTable ) into the new table(tblNonExistingTable) as well as data.


3.  Copy only the data of an existing table into an existing table in other DB:
INSERT INTO [DBName]. dbo.tblDestExistingTable
SELECT * FROM [DBName].dbo.tblSourceExistingTable

The above query will copy all the data of  an source table(tblSourceExistingTable) into the another DB table(tblDestExistingTable).

4.  Copy only the data of an existing table into an existing table in other DB on the basis of some condition:
 INSERT INTO [DBName]. dbo.tblDestExistingTable
SELECT * FROM [DBName].dbo.tblSourceExistingTable Where id > 50

The above query will copy the data of  an source table(tblSourceExistingTable) into the another DB table(tblDestExistingTable) having id of source table(tblSourceExistingTable) greater than 50. So, Lets say, there are 100 records in source table from id 1 to 100, then it will copy only 50 records to destination table.




No comments:

Post a Comment