Copy table from one database to another - sql

I've just created an empty database on my machine. I now wish to copy a table from our server database to this local database.
What sql commands do I need to run to do this? I wish to create the new table, copy data from the old table and insert it into the new table.

Create a linked server to the source server. The easiest way is to right click "Linked Servers" in Management Studio; it's under Management -> Server Objects.
Then you can copy the table using a 4-part name, server.database.schema.table:
select *
into DbName.dbo.NewTable
from LinkedServer.DbName.dbo.OldTable
This will both create the new table with the same structure as the original one and copy the data over.

Assuming that they are in the same server, try this:
SELECT *
INTO SecondDB.TableName
FROM FirstDatabase.TableName
This will create a new table and just copy the data from FirstDatabase.TableName to SecondDB.TableName and won't create foreign keys or indexes.

Another method that can be used to copy tables from the source database to the destination one is the SQL Server Export and Import wizard, which is available in SQL Server Management Studio.
You have the choice to export from the source database or import from the destination one in order to transfer the data.
This method is a quick way to copy tables from the source database to the destination one, if you arrange to copy tables having no concern with the tables’ relationships and orders.
When using this method, the tables’ indexes and keys will not be transferred. If you are interested in copying it, you need to generate scripts for these database objects.
If these are Foreign Keys, connecting these tables together, you need to export the data in the correct order, otherwise the export wizard will fail.
Feel free to read more about this method, as well as about some more methods (including generate scripts, SELECT INTO and third party tools) in this article:
https://www.sqlshack.com/how-to-copy-tables-from-one-database-to-another-in-sql-server/

SELECT ... INTO :
select * into <destination table> from <source table>

INSERT INTO ProductPurchaseOrderItems_bkp
(
[OrderId],
[ProductId],
[Quantity],
[Price]
)
SELECT
[OrderId],
[ProductId],
[Quantity],
[Price]
FROM ProductPurchaseOrderItems
WHERE OrderId=415

If migrating constantly between two databases, then insert into an already existing table structure is a possibility. If so, then:
Use the following syntax:
insert into DESTINATION_DB.dbo.destination_table
select *
from SOURCE_DB.dbo.source_table
[where x ...]
If migrating a LOT of tables (or tables with foreign keys constraints) I'd recommend:
Generating Scripts with the Advanced option / Types of data to script : Data only OR
Resort using a third party tool.
Hope it helps!

Assuming that you want different names for the tables.
If you are using PHPmyadmin you can use their SQL option in the menu. Then you simply copy the SQL-code from the first table and paste it into the new table.
That worked out for me when I was moving from localhost to a webhost.
Hope it works for you!

If you need the entire table structure (not just the basic data layout), use Task>Script Table As>Create To>New Query Window and run in your new database. Then you can copy the data at your leisure.

The quickest way is to use a tool, like RazorSQL or Toad for doing this.

To copy the table from one database to another database, first you have to create the exact table structure for the new table as old one, than copy the table entries from one table to another.
Solution for MySQL database
create table [new database.]<new table name> like [old database.]<old table name>;
insert [new database.]<new table name> select * from [old database.]<old table name>;

Related

SQL Server : creating a table

When creating a table in SQL Server, it is created using dbo.<tableName> format.
I want to change dbo.tableName to source.tableName, as I want to import data into a source table and then cook that data.
Thanks
You are talking about schemas. If the schema source doesn't exist yet, you need to run create schema source. Once the schema exists it's as easy as create table source.tableName (...).

Copy 10k rows from table to table on other server

I cannot use linked server.
Both databases on both servers have the same structure but different data.
I have 10k rows to transfer from the DB on one server to the same DB on the other. I cannot restore the DB on the other server as it will take a huge amount of space that I don't have on the other server.
So, I have 2 options that I don't know how to execute:
Backup and restoring only one table - the table is linked to many other tables but these other tables exist on the other server too. Can I somehow delete or remove the other tables or make a backup only over one table?
I need to transfer 10k rows. How is it possible to create 10k insert queries based on selected 10k rows?
Can I somehow delete or remove the other tables or make a backup only over one table?
No you can not do this, unfortunately
How is it possible to create 10k insert queries based on selected 10k rows?
Right-click on Database -> Tasks -> Generate scripts -> (Introduction) Next
Chose Select specific database objects -> Tables, chose table you need -> Next
Advanced -> Search for Types of data script change from Schema only (by default) to Data only -> OK
Chose where to save -> Next -> Next. Wait the operation to end.
This will generate the file with 10k inserts.
Another way is to use Import/Export wizard (the most simple way for one-time-import/export) if you have link between databases.
There are many ways to choose from, here is one way using BCP. That's a tool that ships with SQL Server to Import and Export Bulk Data.
The outlines of the process:
Export the data from the source server to a file using BCP - BCP OUT for a whole table, or BCP QUERYOUT with a query to select the 10k rows you want exported
Copy the file to the destination server
Import the data using BCP on the destination database - BCP IN.
My suggestion would be to export these rows to excel( you can do this by copy pasting your query output) and transfer this to other server and import it there.
this is the official method :-
https://learn.microsoft.com/en-us/sql/relational-databases/import-export/import-data-from-excel-to-sql
and this is the the unofficial method :
http://therealdanvega.com/blog/2010/08/04/create-sql-insert-statements-from-a-spreadsheet.
Here I have assumed that you only need to transfer the transactional data and your reference data is same on both server. So you will need to execute only one query for exporting your data
I would definietely go down the SSIS route once you use SSIS to do a task like this you will not use anything else very simple to script up. You can use any version and it will be a simple job and very quick.
Open new SSIS project in available visual studio version/s there are many different but even a 2008 version will do this simple task you may have to install integration services or something similar used to be called bids (business information development studio in 2008) (anything up to 2015 although support is nearly there in 2017)
add a data flow task
double click the data flow task
Bottom of screen add two connection managers (1 to source and 1 to destination database)
add oledb source pointing to source database table
add oledb destination pointing to destination database table
drag line between the source and destination (should auto map all columns if the same name)
hit Start and the data will flow very quickly
you have create DbInstaller. using dbInstaller you have share whole database. Dbinstaller work both ado.Net and Entity Frame Work but I have using Entity Frame Work.
you can do it by sql server query
first select first database like
Use database1 --- this will be your first database
after select first database we will put our table row in temp table by this query
select * into #Temp from select * from table1
now we select second database and insert temp table data into second database table by this code
use secondDatabaseName
INSERT INTO tableNameintoinsert (col1, col2, )
SELECT col1, col2 FROM #temp;

How do I copy a SQL Server table with triggers?

I want to copy a SQL Server 2008 R2 database table A1 to create a clone table A1Clone (empty table). Is there any way to do this operation in one shot? Thanks.
Edited:
I tried through SSMS, DB level, Generate Scripts, and I'm able to generate scripts with advanced options to enable scripts to create triggers and indexes.
Wondering if there is any other shortcut to copy over the whole table object.
If you are asking ,how to copy table related objects like indexes,triggers in one go..you can't do that by normal ways like select into...Your options
generate scripts of existing object,on which you want to perform operation..
normal way of creating entirely

Copy database schema to an existing database

I'm using Microsoft Sql Server Management Studio.
I currently have an existing database with data in it, which I will call DatabaseProd
And I have a second database with data used for testing, so the data isn't exactly correct nor up to date. I will call this database DatabaseDev.
However DatabaseDev now contains newly added tables and newly added columns,etc etc.
I would like to copy this new schema from DatabaseDev to DatabaseProd while keeping the DatabaseProd's Data.
Ex.
DatabaseProd contains 2 tables
TableA with column ID and Name
TableB with column ID and jobName
and these tables contains data that I would like to keep
DatabaseDev contains 3 tables
TableA with column ID ,Name and phoneNum
TableB with column ID and jobName
TableC with column ID and document
and these tables contains Data that I dont need
Copy DatabaseDev Schema to DatabaseProd but keep the data from DatabaseProd
So DatabaseProd after the copy would look like this
TableA with column ID ,Name and phoneNum
TableB with column ID and jobName
TableC with column ID and document
But the tables would contain it's original Data.
Is that possible?
Thank you
You can use Red-Gate SQL Compare, this will allow you to compare both DB's and generate a script to run on the source DB. You have to pay for a license, but you will get a 14-day trial period.
This tool, along with Data Compare and two tools I always insist on with new roles as they speed up development time, and minimise human error.
Also, a good tip when using SQL compare - if you need to generate a rollback script, then you can edit the project (after creating your rollout script), switch the source and destination around and this will create a script which will return the schema back to it's original state if the rollout script fails. However, be very careful when doing this, and don't select synchronize with sql compare, rather generate a script, see image. I can't upload an image, but I have linked to one here - you can see the two options to select Generate Script / Sync using SQL compare.
Yes, you can just generate a database script which is just for schema only no data will added to that script.
Also you need to just select the third table while creating or generating the database script and run that script to your production server database it will create a new table (table 3 in your case) without any data.
For more information about how to create a database script please follow the below link:
http://blog.sqlauthority.com/2011/05/07/sql-server-2008-2008-r2-create-script-to-copy-database-schema-and-all-the-objects-data-schema-stored-procedure-functions-triggers-tables-views-constraints-and-all-other-database-objects/
You need an ALTER TABLE statement
ALTER TABLE tableA ADD PhoneNum Varchar(10) --Insert variable of choice here
Looked like no changes to TableB
Add TableC
CREATE TABLE TableC (ColumnID int, Document Varvhar(50))
DO you need to copy constraints, Indexes or triggers over?

copy tables with data to another database in SQL Server 2008

I have to copy the tables with data from one database to another using Query. I know how to copy tables with data within a database. But I was not sure about how to do the same for copying between two databases.
I have to copy huge number of tables, so I need any fast method using query...
Anybody please help out...Thanks in advance...
You can use the same way to copy the tables within one database, the SELECT INTO but use a fully qualified tables names database.schema.object_name instead like so:
USE TheOtherDB;
SELECT *
INTO NewTable
FROM TheFirstDB.Schemaname.OldTable
This will create a new table Newtable in the database TheOtherDB from the table OldTable whih belongs to the databaseTheFirstDB
Right click on the database, select tasks and click on Generate Scripts.
In the resultant pop-up, choose options as required (click advanced), to drop and create table, drop if exists, etc.
Scroll down and choose "Schema and Data" or "Data Only" or "Types of data to script (2008 R2)"as required.
Save to file and execute on the destination DB.
Advantages -
Can be executed against the destination DB, even if it is on another server / instance
Quickly script multiple tables, with data as needed
Warning - Might take quite a while to script, if the tables contain a large amount of data.
Rajan
INSERT INTO DB2.dbo.MyOtherTable (Col0, Col1)
SELECT Col0, Col1 FROM DB1.dbo.MyTable
Both table column's must have same data types..
Below SQL Query will copy SQL Server table schema & data from one database to another database. You can always table name (SampleTable) in your destination database.
SELECT * INTO DestinationDB.dbo.SampleTable FROM SourceDB.dbo.SampleTable