Wednesday, 2 November 2011

MSSQL - how to copy tables and data


problem

MSSQL - how to copy
- How to copy a table’s structure to another database?
- How to create a table with the same structure (fields) on the
- How to copy the data of the table to another table?
difficulty level

4/10 :)
compatibility

general
solution

How to copy a table’s structure to another database?
The follow code, not only copy’s the structure but also copies and the records of it. You may filter the data applying a “where” as I do here.
--
Do like:
SELECT * INTO [TargetDatabase].[dbo].[MyTable]
FROM [SourceDatabase].[dbo].[MyTable]
where [SourceDatabase].[dbo].[MyTable].CustomerCode='01'; -- where is optional


How to create a table with the same structure (fields) on the same database?
(Like you did previously!)
--Do like:
SELECT * INTO MyNewTable
FROM MySourceTable
where MySourceTable.CustomerCode='01'; -- where is optional

How to copy the data of the table to another table?
--Syntax:
INSERT INTO TargetTable( <field list> )
SELECT <field list> FROM SourceTable
--Do like:
INSERT INTO NewCustomers
( Company, Branch, Name )
SELECT
Company, Branch, Name
FROM Customers
Where Branch=’01’; -- where is optional

No comments:

Post a Comment