Cross-server SQL - sql

I want to port data from one server's database to another server's database.
The databases are both on a different mssql 2005 server.
Replication is probably not an option since the destination database is generated from scratch on a [time interval] basis.
Preferebly I would do something like
insert *
from db1/table1
into db2/table2
where rule1 = true
It's obvious that connection credentials would go in somehwere in this script.

I think what you want to do is create a linked server as per this webarchive snapshot of msdn article from 2015 or this article from learn.microsoft.com. You would then select using a 4 part object name eg:
Select * From ServerName.DbName.SchemaName.TableName

You can use Open Data Source Like this :
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO
SELECT *
FROM OPENDATASOURCE('SQLOLEDB',
'Data Source=<Ip Of Your Server>;
User ID=<SQL User Name>;Password=<SQL password>').<DataBase name>.<SchemaName>.<Table Or View Name>
Go

Are SQL Server Integration Services (SSIS) an option? If so, I'd use that.

Would you be transferring the whole content of the database from one server to another or just some data from a couple of tables?
For both options SSIS would do the job especially if you are planning to to the transfer on a regular basis.
If you simply want to copy some data from 1 or 2 tables and prefer to do it using TSQL in SQL Management Studio then you can use linked server as suggested by pelser
Set up the source database server as a linked server
Use the following syntax to access data
select columnName1, columnName2, etc from serverName.databaseName.schemaName.tableName

Well I don't agree with your comment on replication. You can start a replication by creating a database from scratch, and you can control either the updates will be done by updating the available client database or simply recreating the database.
Automated replication will ease your work by automatically managing keys and relations.
I think the easiest thing to do is to start a snapshot replication through MSSQL Server Studio, get the T-SQL corresponding scripts (ie the corresponding T-SQL instructions for both publication and subscriptions), and record these scripts as part of a job in the Jobs list of the SQL Agent or as a replication job in the replications folder.

You could go the linked server route.
you just can't use the select * into you have to do an insert into select.
I would avoid replication if you don't have experience with it as it can be difficult to fix if it breaks and can be prone to other problems if not properly managed.
Keep it simple especially if the databases are small.

Can you use the Data Transformation Services to do the job? This provides all sorts of bolt-together tools for doing this kind of thing.
You can download the SQL Server 2005 feature pack from Microsoft's website
here

CREATE VIEW newR1
AS
SELECT * from OPENQUERY ([INSTANCE_NAME], 'select * from DbName.SchemaName.TableName')

Related

SQL Azure - copy table between databases

I am trying to run following SQL:
INSERT INTO Suppliers ( [SupplierID], [CompanyName])
Select [SupplierID], [CompanyName] From [AlexDB]..Suppliers
and got an error "reference to database and/or server name in is not supported in this version of sql server"
Any idea how to copy data between databases "inside" the server?
I can load data to client and then back to server, but this is very slow.
I know this is old, but I had another manual solution for a one off run.
Using SQL Management Studio R2 SP1 to connect to azure, I right click the source database and select generate scripts.
during the wizard, after I have selected my tables I select that I want to output to a query window, then I click advanced. About half way down the properties window
there is an option for "type of data to script". I select that and change it to "data only", then I finish the wizard.
All I do then is check the script, rearrange the inserts for constraints, and change the using at the top to run it against my target DB.
Then I right click on the target database and select new query, copy the script into it, and run it.
Done, Data migrated.
Since 2015, this can be done by use of elastic database queries also known as cross database queries.
I created and used this template, it copies 1.5 million rows in 20 minutes:
CREATE MASTER KEY ENCRYPTION BY PASSWORD = '<password>';
CREATE DATABASE SCOPED CREDENTIAL SQL_Credential
WITH IDENTITY = '<username>',
SECRET = '<password>';
CREATE EXTERNAL DATA SOURCE RemoteReferenceData
WITH
(
TYPE=RDBMS,
LOCATION='<server>.database.windows.net',
DATABASE_NAME='<db>',
CREDENTIAL= SQL_Credential
);
CREATE EXTERNAL TABLE [dbo].[source_table] (
[Id] BIGINT NOT NULL,
...
)
WITH
(
DATA_SOURCE = RemoteReferenceData
)
SELECT *
INTO target_table
FROM source_table
Unfortunately there is no way to do this in a single query.
The easiest way to accomplish it is to use "Data Sync" to copy the tables. The benefit of this is that it will also work between servers, and keep your tables in sync.
http://azure.microsoft.com/en-us/documentation/articles/sql-database-get-started-sql-data-sync/
In practise, I haven't had that great of an experience with "Data Sync" running in production, but its fine for once off jobs.
One issue with "Data Sync" is that it will create a large number of "sync" objects in your database, and deleting the actual "Data Sync" from the Azure portal may or may not clean them up. Follow the directions in this article to clean it all up manually:
https://msgooroo.com/GoorooTHINK/Article/15141/Removing-SQL-Azure-Sync-objects-manually/5215
SQL-Azure does not support USE statement and effectively no cross-db queries. So the above query is bound to fail.
If you want to copy/backup the db to another sql azure db you can use the "Same-server" copying or "Cross-Server" copying in SQL-Azure. Refer this msdn article
You could use a tool like SQL Data Compare from Red Gate Software that can move database contents from one place to another and fully supports SQL Azure. 14-day free trial should let you see if it can do what you need.
Full disclosure: I work for Red Gate Software
An old post, but another option is the Sql Azure Migration wizard
Use the following steps, there is no straight forward way to do so. But by some trick we can.
Step1 : Create another one table with the same structure of Suppliers table inside [AlexDB], Say it as SuppliersBackup
Step2 : Create table with the same structure of Suppliers table inside DesiredDB
Step3 : Enable Data Sync Between AlexDB..Suppliers and DesiredDB..Suppliers
Step4 : Truncate data from AlexDB..Suppliers
Step5 : Copy data from AlexDB..SuppliersBackup to AlexDB..Suppliers
Step6 : Now run the sync
Data Copied to DesiredDB.
If you have onprem version that has the sp_addlinkedsrvlogin, you can setup Linked Servers for both source and target database then you can run your insert into query.
See "SQL Server Support for Linked Server and Distributed Queries against Windows Azure SQL Database" in this blog: https://azure.microsoft.com/en-us/blog/announcing-updates-to-windows-azure-sql-database/
Ok, i think i found answer - no way. have to move data to client, or do some other tricks. Here a link to article with explanations: Limitations of SQL Azure: only one DB per connection
But any other ideas are welcome!
You can easily add a "Linked Server" from SQL Management Studio and then query on the fully qualified table name. No need for flat files or export tables. This method also works for on-prem to azure database and vice versa.
e.g.
select top 1 ColA, ColB from [AZURE01_<hidden>].<hidden>_UAT_RecoveryTestSrc.dbo.FooTable order by 1 desc
select top 1 ColA, ColB from [AZURE01_<hidden>].<hidden>_UAT_RecoveryTestTgt.dbo.FooTable order by 1 desc
A few options (rather workarounds):
Generate script with data
Use data sync in Azure
Use MS Access (import and then export), with many exclusions (like no GUID in Access)
Use 3-rd party tools like Red Gate.
Unfortunately no easy and built-in way to do that so far.
I would recommend SSMS SQL Server Import and Export feature. This feature supports multiple connection configurations and cross-server copy of selected tables. I have tried .NET Sql Server connector, which works very well for the Azure SQL databases.

Create SQL script that create database and tables

I have a SQL database and tables that I would like to replicate in another SQL Server. I would like to create a SQL script that creates the database and tables in a single script.
I can create "Create" script using the SQL Management Studio for each case (Database and Tables), but I would like to know if combining the both "Create" scripts into single script would be enough.
Thanks.
Although Clayton's answer will get you there (eventually), in SQL2005/2008/R2/2012 you have a far easier option:
Right-click on the Database, select Tasks and then Generate Scripts, which will launch the Script Wizard. This allows you to generate a single script that can recreate the full database including table/indexes & constraints/stored procedures/functions/users/etc. There are a multitude of options that you can configure to customise the output, but most of it is self explanatory.
If you are happy with the default options, you can do the whole job in a matter of seconds.
If you want to recreate the data in the database (as a series of INSERTS) I'd also recommend SSMS Tools Pack (Free for SQL 2008 version, Paid for SQL 2012 version).
In SQL Server Management Studio you can right click on the database you want to replicate, and select "Script Database as" to have the tool create the appropriate SQL file to replicate that database on another server. You can repeat this process for each table you want to create, and then merge the files into a single SQL file. Don't forget to add a using statement after you create your Database but prior to any table creation.
In more recent versions of SQL Server you can get this in one file in SSMS.
Right click a database.
Tasks
Generate Scripts
This will launch a wizard where you can script the entire database or just portions. There does not appear to be a T-SQL way of doing this.
An excellent explanation can be found here: Generate script in SQL Server Management Studio
Courtesy Ali Issa Here's what you have to do:
Right click the database (not the table) and select tasks --> generate scripts
Next --> select the requested table/tables (from select specific database objects)
Next --> click advanced --> types of data to script = schema and data
If you want to create a script that just generates the tables (no data) you can skip the advanced part of the instructions!
Not sure why SSMS doesn’t take into account execution order but it just doesn’t. This is not an issue for small databases but what if your database has 200 objects? In that case order of execution does matter because it’s not really easy to go through all of these.
For unordered scripts generated by SSMS you can go following
a) Execute script (some objects will be inserted some wont, there will be some errors)
b) Remove all objects from the script that have been added to database
c) Go back to a) until everything is eventually executed
Alternative option is to use third party tool such as ApexSQL Script or any other tools already mentioned in this thread (SSMS toolpack, Red Gate and others).
All of these will take care of the dependencies for you and save you even more time.
Yes, you can add as many SQL statements into a single script as you wish. Just one thing to note: the order matters. You can't INSERT into a table until you CREATE it; you can't set a foreign key until the primary key is inserted.

Efficiently moving large sets of data between SQL Server tables?

I have a rather large (many gigabytes) table of data in SQL Server that I wish to move to a table in another database on the same server.
The tables are the same layout.
What would be the most effecient way of going about doing this?
This is a one off operation so no automation is required.
Many thanks.
If it is a one-off operation, why care about top efficiency so much?
SELECT * INTO OtherDatabase..NewTable FROM ThisDatabase..OldTable
or
INSERT OtherDatabase..NewTable
SELECT * FROM ThisDatabase..OldTable
...and let it run over night. I would dare to say that using SELECT/INSERT INTO on the same server is not far from the best efficiency you can get anyway.
Or you could use the "SQL Import and Export Wizard" found under "Management" in Microsoft SQL Server Management Studio.
I'd go with Tomalak's answer.
You might want to temporarily put your target database into bulk-logged recovery mode before executing a 'select into' to stop the log file exploding...
If it's SQL Server 7 or 2000 look at Data Transformation Services (DTS). For SQL 2005 and 2008 look at SQL Server Integration Services (SSIS)
Definitely put the target DB into bulk-logged mode. This will minimally log the operation and speed it up.

How do I make a script in SQL Management Studio 2005?

I have a table in an MS SQL Server db. I want to create a script that will put the table and all records into another db. So I right-click the table in Management Studio and select Create-To new query editor... but all I get is the table structure.
How exactly do I get the values too?
One of the things I really like about the tools for MySQL that SQL Server is missing out of the box to be certain.
You can use a script to do it however.
You might also want to consider using something like Red-Gate SQL Compare and Red-Gate SQL Data Compare. They aren't cheap tools, priced at $395 each (for the standard editions), but there are 14 day free trials available for download, and they make copying schema and data from one SQL Server to another very easy.
If both are on the same machine (or on different machines but the servers are linked)
you can create the table with the script you can generate automatically and do this to copy the data:
INSERT INTO [destinationdb].[dbo].[destinationtable] SELECT *
FROM [originaldb].[dbo].[originaltable]
(Prepend [servername] to the database name if you'll be using linked servers)
Another option is to enable xp_cmdshell (do with care, it's relaxing security constraints) and use the bcp command line utility from the management studio to create copies you can then import into the other database/server. You can do that directly from the shell as well and do not need to enable xp_cmdshell in that case, of course.
it doesn't really create a "SQL script" but it does the job :
select the database in the object explorer
right click
select import/export data
follow the wizard
at the end of the process you can save the "integration service package" to reuse it
later you can modify the details by opening the .dtsx
(it will take care of security, and won't cost one more penny, it's seems we have to compete with other answers :) )
hope it helps.

Backup SQL Schema Only?

I need to create a backup of a SQL Server 2005 Database that's only the structure...no records, just the schema. Is there any way to do this?
EDIT: I'm trying to create a backup file to use with old processes, so a script wouldn't work for my purposes, sorry
Use a 3 step process:
Generate a script from the working database
Create a new database from that script
Create a backup of the new database
Why not just use SQL Management Studio to create a complete script of your database and the objects?
Toad for SQL Server does this nicely, if you're considering a commercial product.
I make heavy use of this tool:
SQLBalance for MySQL
Unfortunately; its windows only... but works like a charm to move databases around, data or no data, merge or compare.
As of SQL Server 2012 (patched), you can make a schema only clone of your database using DBCC CLONEDATABASE. Then simply backup the clone.
dbcc clonedatabase(Demo, Demo_Clone) with verify_clonedb;
alter database [Demo_Clone] set read_write;
backup database [Demo_Clone] to disk = N'C:\temp\Demo_SchemaOnly_20220821.bak';
drop database [Demo_Clone];
Read more here: Schema Only Database Backup