Transferring data from one database to another - sql-server

I have two databases, lets say Database A and B, with different datastructures.
In Database A there is a table contacts.
In Database B there is a table Accounts.
I want to transfer data from Database A table contacts to Database B table Accounts.
I am use SQL Server 2005 and want to write sql scripts to do this.
Can someone tell me what's the easiest and most efficient way to achieve this:
a) If they are on the same SQL server
b) If they are on different SQL servers.

The easiest method isn't necessarily the most efficient. SSIS is likely the most efficient, as Mitch already indicated.
The easiest (if you don't know SSIS already) is to just set up a linked server to the remote DB, and SELECT the data across using four-part naming. You set up a linked server using sp_addlinkedserver and sp_addlinkedsrvlogin (check BOL for the syntax), and query as follows:
INSERT INTO MyLocalTable (ColumnList)
SELECT <Columns> FROM RemoteServer.RemoteDB.RemoteSchema.RemoteTable

Use SSIS. It will work for both local and remote cases, and will enable you to set up a transform between the tables, to map columns to lother columns etc.

Is it a one off transfer? If it's a simple transfer I write a SELECT statement to create the INSERT statements, i.e.
SELECT 'INSERT INTO Accounts (ID, Name) VALUES (' + CAST(ID as VARCHAR) + ', ''' + Name + ''')'
FROM Contacts
Run this on Database A - and it will spit out the all INSERT statements, which you copy and paste so you can run them on Database B.
Or, on the same database:
INSERT INTO DatabaseA.dbo.Accounts (ID, Name)
SELECT Id, Name
FROM DatabaseB.dbo.Contacts
Still not happy - try setting up linked servers: http://msdn.microsoft.com/en-us/library/aa213778(SQL.80).aspx

Related

How to loop on multiple databases and tables

I have a SQL Server instance which contains multiple databases. I have 2 tables which exist in all databases on the server:
Refresh Log
Detailed refresh log.
I want to union all the tables across all databases on the server so the final result will be 2 tables which are the union refresh log and detailed refresh log.
I need help to write the function which runs across all databases.
I'm also a little uncertain as to what you're hoping for, for example if you need the resulting output to be in two permanent tables or if you just need the result when queried. Of course once you build your SELECT you can return it to the caller or put it into a table, so I'll leave that up to you.
If your databases are unchanging, then of course you can just write your query and maybe put it into a VIEW for convenience:
SELECT columns from database1.dbo.RefreshLog
UNION ALL
SELECT columns from database2.dbo.RefreshLog
...
and so on
But if you're saying that your databases are themselves dynamic, in other words that databases may be created or dropped over the lifetime of your project, then you could consider using the "undocumented" procedure sp_msforeachdb to build up a list of databases, and then use THAT list to build your UNION query. Here's a quick script that captures the names of all databases that include a specific table ("Products" in the example):
IF object_id('tempdb..#DatabaseNames') IS NOT NULL
DROP TABLE #DatabaseNames
CREATE TABLE #DatabaseNames (DatabaseName SYSNAME)
execute sp_msforeachdb #command1=
N'IF EXISTS(SELECT * FROM [?].sys.tables WHERE Name = ''Products'')
INSERT #DatabaseNames VALUES(N''Database [?]'')'
SELECT * FROM #DatabaseNames

Where did my new table go

I have a database called mbt. I wanted to write some data from temporary table to real table.
--I used this query.
SELECT * INTO new_table FROM #tmp
when i runned the query it returned normal message.
15813 row(s) affected
After that i checked my tables in mbt database, but i couldn't see 'new_table'
how could such a thing be, where the table might have gone.
I may have forgotten to use 'use MBT' statment at the beginning of the query. Does it make problem
I'm using ms sql server 2014(SP2)(KB3171021)-12.0.5000.0(X64)
ANSWER
It gone to Master DB
select 'master' as DatabaseName,
T.name collate database_default as TableName
from master.sys.tables as T
It Will create a new table on your database. but you did not use so it will store in master database on your server.
Run the query below to find databases which have the object new_table:
sp_MSForEachDB 'Use [?] IF EXISTS (SELECT 1 FROM sys.objects WHERE name= ''new_table'')
SELECT DB_NAME()'
I had the same problem. What i did is, I rewrite the statement of use Database and then refresh the database browser after that i got Result. You can try it. may be it will help you.
Always use command "USE db_name" to make sure that you are querying right database.
Below command will show all databases available on the server.
SHOW DATABASES;
If you are using GUI tool to connect DB server, there is a possibility that at the time of connection you got connected to different DB. If you executed the query to create table and inserted record. These records are inserted in new table in different DB than mbt.

SQL Server : gather data from different databases

I have many different application databases with a [Log] table. I have one central database with a similar log table, but with one extra column called TenantId. There is also a Tenant table with a TenantId and a DatabaseName column. These DatabaseName contain the names of the application databases.
Now I want to loop all the application databases and copy the log entries to the central log table, with the TenantId that belongs to the application database name.
Would it be possible to write one procedure in the central database instead of creating many procedures in the application databases? All databases are on the same SQL Server instance.
Just some quick Dynamic SQL. In the example below, CHINRUS is my central database and would therefore be excluded from consolidation.
I should add, that the WHERE should be tailored to exclude any misc database on the server. Yet another option would be to maintain a table which has the proper definitions.
Declare #LogTable varchar(100)='[Chinrus].[dbo].[TransactionLog]'
Declare #CentralDB varchar(100)='Chinrus'
Declare #SQL varchar(max) = ''
Select #SQL = #SQL + SQL
From (
Select Name,SQL=';Insert Into '+#LogTable+' Select *,TenantId='''+Name+''' From ['+Name+'].[dbo].[TransactionLog] '
From master.dbo.sysdatabases
Where Name<>#CentralDB
) A
Select #SQL
--Exec(#SQL)
You can get list of all databases with following query:
SELECT name
FROM master.dbo.sysdatabases
and then you can use a cursor to get each database data and insert in one table in current database.

Firebird copy from one database using isql

I've got 2 firebird databases
c:\db1.gdb
c:\db2.gdb
both databases schema's are the same so both contain a table
MyTable
-------
Id int
Name varchar(50)
...etc
Its guaranteed that the data is different on both databases, however I need to copy from db2.MyTable into db1.MyTable
A requirement is that I do this using the firebird isql tool.
How would I firstly using isql
-Connect to both db's in one isql command window
-run a sql statement that would do a select all from one table in db2 and insert it into the same table in db1
I'm using firebird 1.5
This is not possible with FB 1.5. You can do this with Firebird 2.5 using the new "execute statement...external" feature that makes it possible to access another firebird database from inside triggers, procedures and code blocks.
If you really must do it using isql then you could write select statement which produces insert statements; run the select in db2, save the result into some file and then execute the statements in db1. The select statement would be something like
select 'insert into MyTable(id, name) values ('|| cast(id as varchar(10)) ||','''|| name ||''');' from MyTable;
However the job is much easier to do using something like Clever Components' Interbase DataPump.

Is it possible to copy the data in a remote MSSQL table to a local Table?

What is the best way to go about doing this? I have found some INSERT statements, but they all seem to work just for inner-database copying.
My rendition:
INSERT INTO [PROGRAM003].[dbo].[faq]
([id], [category], [question], [answer], [tags])
SELECT ([id], [category], [question], [answer], [tags])
FROM [SQL2005_552664_gsow].[dbo].[faq]
I am not very fluent with MSSQL yet, so any and all help is appreciated.
How "remote" are we talking? If it's another database on the same server you can just prepend the database name, as your initial example showed:
INSERT INTO [mytable] SELECT * FROM [database].dbo.[table]
If it's on a completely different server, you need to set them up as linked servers. Then you can do this:
INSERT INTO [mytable] SELECT * FROM [server].[database].dbo.[table]
You must, of course, fully specificy the database and schema within that server as well, and expect performance to suffer because it will need to move data across the network.
You can use OPENDATASOURCE or OPENROWSET to access tables on other servers. You'll need to provide SQL credentials in the query or have both databases setup to allow access to your windows id for this to work. You can also use the import/export wizard in SQL Server Management Studio -- right click on the database and choose Tasks-->Import or Tasks-->Export.
USE master
GO
EXEC sp_addlinkedserver
#server = 'RemoteSer',
#srvproduct = '',
#provider = 'MSDASQL',
#provstr = 'DRIVER={SQL Server};SERVER=000.000.000.000\SQLEXPRESS;'
GO
SELECT * INTO bnkWeb.dbo.test1 FROM [RemoteSer].[bnk].[dbo].[test1]
You might want to look into DTS or (2005+) Integration Services. Both of these will take data from one DB (Table) and copy the data into another DB (Table).
Link to Integration Services: http://msdn.microsoft.com/en-us/library/ms141091.aspx

Resources