SQL Server, execute batch T-SQL script on multiple databases - sql-server

Our SQL Server 2000 instance hosts several databases which are all similar, one for each of our client. When comes the time to update them all, we use Red Gate SQL Compare to generate a migration script between the development database and a copy of the current state DB of all the clients database.
SQL Compare generates a script which is transactional, if one step fails, the script rolls back everything. But currently our system uses a method that splits the script on batch separators (the GO statement) and then runs each command separately, which ruins all the transactional stuff. The GO statement is not supported when querying the database by programmation (in classic ASP)
I want to know how I could run that script (keeping the transactions) on all those databases (like 250 DB), programmatically or manually in a tool? In Query Analyzer, we need to select each DB and press Run which is quite long for the number of DB we have.

If you can use SSMS from SQL 2005 or 2008, then I'd recommend the free SSMS Tool pack

I use external sqlcmd command line tool. I have the same situation on the server I work.
I have the script in *.sql file and the list of databases on the 2nd file. I have small *.bat script which iterate through all the databases and execute script using sqlcmd command.
In more details I have like this:
DB.ini file with all the databases on which I want to deploy my script
sql/ directory where I store all scripts
runIt.bat - script which deploys scripts
The command line looks more-less like this:
sqlcmd -S <ComputerName>\<InstanceName> -i <MyScript.sql> -d <database_name> -T
In SQL Server 2000 it was osql utility
UPDATE
Red Gate now have a tool called SQL Multi Script, which basically does exactly what you want. I supports SQL 2000 to 2008 R2 and running queries on multiple databases in parallel which improve performance.

7 years later i had the same issue so many times so I made it and published the project:
TAKODEPLOY
Here are some features:
Get all databases from a single instance and apply a name filter. Or just a single direct connection.
Mix database sources as much as you want. Example, two direct and one full instance with or withut a filter.
Script editor (Avalon Text, same monodevelop uses)
Scripts are parsed and errors are detected before executing.
Scripts are 'splitted' by GO statements.
Save your deployment into a file
Get a list of all databases before deploying.
See in realtime what is happening (PRINT statements are recommended here!).
Automatic rollback to independent database if any error occurs.
Transparent Updates via Squirrel.
You can get it at: https://github.com/andreujuanc/TakoDeploy

Not sure if this will work, but try replacing the GO statements with semicolons, and running the entire statement in one batch.

If I recall, you can also create a script in SQL Compare to change everything back to the state it started in. You might want to generate both.
When I did this sort of deployment (it's been awhile), I first loaded to a staging server that was made exactly like prod before I started to make sure the scripts would work on prod. If anything failed (usually because of the order that scripts were run, can't set a foreign key to a table that doesn't exist yet for instance). I also scripted al table changes first, then all view changes, then all UDF changes, then all stored proc changes. This cut down greatly onthe failures due to objects not yet existing, but I still usually had a few that needed to be adjusted.

Related

SQL Server - copy all data from all tables from one server to another server with identical structure

I want to copy all data from all tables from one SQL server database to another existing SQL server database of the same structure. I have a script to initially delete all contents of all tables in my output database before proceeding so that it is 'fresh' for the copy.
I understand that 'select into' statements can get this done but I want to be able to do it in bulk. I want to emulate the behavior that works very well in Management Studio of:
Right-click a DB
Select 'Tasks'
Select 'Export Data...'
In here, I can select an output DB and then select all tables. The transfer goes straight through without issue. I cannot find a command line way to achieve this.
The reason I am after this is that we want a daily copy of the prod database in a testing environment, so need to task schedule this process to run each night.
Due to some contstraints, I can't use a bacpac in this case.
Using the import/export task in SSMS, the last step has 2 options. Run immediately or save as SSIS package. So - save it as a SSIS package. You can then run this package whenever you want. And yes - you will need to do this twice. Once for export, once for import. You can also do exactly the same thing using SSIS btw.
So how do you execute a package from the command line? Like you do for any question, you should search first. Some suggestions/examples are here.
And if needed, you can schedule this using the agent.

Create a copy of production databases, without any data?

I need to create a copy of all of our production databases (SQLServer), without any data.
I need to do this on a regular basis, preferably scheduled and not manually.
Do I have to write code that extracts from systables and builds whe SQL-statements itself or is there a good way to do this?
As there is a method to do that in SQL Management Studio:
Select a database
right click
tasks
generate script
etc ...
You can then save the script generated as an sql file.
Once the script set, and if it is T-SQL, you can just add it to the jobs of your server. .And if you have only a SQL EXPRESS server (with no job schedule), I remember it was possible, a few years ago, to find some free products on the net that would do the job.

Want to create a script to export Data and tables and views to a sql script

Want to create a script to export Data and tables and views to a sql script.
I have SQL Server 2008 r2.
So far I've only been able to automatically generate an sqlscript for all tables and views. But the data wasn't included.
OR is there any easier way to export data, tables, views, from one SQL Server to my ISP's SQL server?
Regards
Tea
If for some reason a backup/restore won't work for you, SSMS' Generate Scripts tool includes an advanced scripting option to include data:
Here are some options to think over (prioritised in terms of what I would recommend):-
A simple backup and restore will be the easiest and quickest solution;
Using a data scripting tool (like Red-Gate's Data Compare) could solve your needs;
Use the database comparison as part of Visual Studio.
A SSIS package could be developed to pump data back and forth between the two instances; or
Write your own script using the SET IDENTITY INSERT ON / OFF command for the identity seeded tables
The easiest way to do this is to create a backup, copy the .bak file to the other server, and restore the backup there.
Like #jhewlett said that will be the best way to do it. to answer the question in the comment section. no it shouldn't be a problem. Just make sure that the SQL Server Versions are the same. Had a bit of an issue not to long ago where there were two pc's with different releases of the R2 installed and couldn't restore the backup. Other thing you can also do is to script the entire database with data, but this will not be recommended as it could take a long time to generate the script and for it to finish running on the other computer.
Or you can simply just stop the SQL server instance and copy the database away onto an external hard drive and re-attach it to the other server. just remember to start the instances after doing this step.
I use Navicat Premium for these kind of things in mysql. It generates sql from data, tables, views and anything else. It provides tools to copy or synchronize table from one database on different server or platforms as well. For example I use it so much to transfer my tables from MySQL to a SQLite database, So easy and fast. Otherwise I had to transfer it manually with so much trouble.
very good tool and required for any DB admin or programmer. It support MySQL, Oracle, MS SQL Server, PostgreSQL and SQLite.
To Generate a schema with data follow these steps.
Select database to generate a schema '>' right click '>' Tasks '>' Generate schema '>' click NEXT in popup window '>'
select DB object to generate schema and click NEXT '>'
Go to advance option and scroll down '>'
Find Type of data to script and select one option as you need. '>'
and then Next Next and finish it.
Enjoy it.
If you don't want to port all tables data (for example you need to port just some base data in special tables) scripting options is not useful for you. In this case you'll have two options. First is using some third parties tools such as Red-Gate and Second way is writing the script by yourself. I prefer Second option because except the expensive price of most of them i want to run just little script for little delete, update and inserting purpose. But the important problem is here: maybe the record count is too long to write scripts record by record. I Think the linked Server is good point to solve that. It's enough for describing Just Declare Linked Server as you see in Images and get new script in your source DB and write scripts with access to both source and destination DB. Attached image must be clear.
Create New Linked Server:
Write Destination SQL Server Address:
Fill Login Info:
Now you have Linked Server:
Write script and enjoy:
Hope this help.

How to sync schema continuously in two databases in Sql Server (for unit testing)

We have a database against which we run unit tests for components that require a database (for several reasons we are not mocking the DAL everywhere).
We are using Sql Server 2008 R2 and in the development db server we have our development database (ApplicationName_Dev) and our testing db (ApplicationName_UT).
The unit tests create the test data they need and delete it afterwards so the tables could/should be empty when no tests are running.
The problem is keeping the schema of the unit test database up to date.
The best solution for me (to my limited knowledge) would be to have a Sql Server Agent Job that would run once a night (or when manually started) that would drops all the tables in the UT database, generate a create script for all tables, indexes and relationships in the Dev-database, and run the create scripts on the UT-database. Note that we don't need to insert any data.
Is there any way of programmatically (T-Sql, SMO etc) generating Create scripts for all tables including indexes and relationships?
In Management Studio I can right click the database->Tasks->Generate scripts...->Choose Objects->Tables and I get just the scripts that I want (except for the "Use [ApplicationName_Dev]" on the first line.
Please help.
Regards,
Mathias
I'd create an SSIS package - there's a task called "Transfer SQL Server Objects Task". Specify your Source and Destination Connections & Databases, set DropObjectsFirst to True, and CopyAllObjects (or just CopyAllTables and CopyAllViews) also, and you should be set. (And obviously, don't set CopyData to true).
You also need to set the CopyIndexes and other such table options, for those table structures you want.
Setting up a job to run an SSIS package is also quite easy.
You could use a tool like SQL Delta. You create a "script" (SQL Delta specific script) using SQL Delta and essentially , what you can do is get it to sync the source database with the destination database. It can also pump in data into some or all tables if needed.
The whole process can be automated using a scheduled job using the Scheduler (part of Windows).

Copy table to a different database on a different SQL Server

I would like to copy a table from one database to another. I know you can easily do the following if the databases are on the same SQL Server.
SELECT * INTO NewTable FROM existingdb.dbo.existingtable;
Is there any easy way to do this if the databases are on two different SQL Servers, without having to loop through every record in the original table and insert it into the new table?
Also, this needs to be done in code, outside of SQL Server Management Studio.
Yes. add a linked server entry, and use select into using the four part db object naming convention.
Example:
SELECT * INTO targetTable
FROM [sourceserver].[sourcedatabase].[dbo].[sourceTable]
If it’s only copying tables then linked servers will work fine or creating scripts but if secondary table already contains some data then I’d suggest using some third party comparison tool.
I’m using Apex Diff but there are also a lot of other tools out there such as those from Red Gate or Dev Art...
Third party tools are not necessary of course and you can do everything natively it’s just more convenient. Even if you’re on a tight budget you can use these in trial mode to get things done….
Here is a good thread on similar topic with a lot more examples on how to do this in pure sql.
SQL Server(2012) provides another way to generate script for the SQL Server databases with its objects and data. This script can be used to copy the tables’ schema and data from the source database to the destination one in our case.
Using the SQL Server Management Studio, right-click on the source database from the object explorer, then from Tasks choose Generate Scripts.
In the Choose objects window, choose Select Specific Database Objects to specify the tables that you will generate script for, then choose the tables by ticking beside each one of it. Click Next.
In the Set Scripting Options window, specify the path where you will save the generated script file, and click Advanced.
From the appeared Advanced Scripting Options window, specify Schema and Data as Types of Data to Script. You can decide from here if you want to script the indexes and keys in your tables. Click OK.
Getting back to the Advanced Scripting Options window, click Next.
Review the Summary window and click Next.
You can monitor the progress from the Save or Publish Scripts window. If there is no error click Finish and you will find the script file in the specified path.
SQL Scripting method is useful to generate one single script for the tables’ schema and data, including the indexes and keys. But again this method doesn’t generate the tables’ creation script in the correct order if there are relations between the tables.
Microsoft SQL Server Database Publishing Wizard will generate all the necessary insert statements, and optionally schema information as well if you need that:
http://www.microsoft.com/downloads/details.aspx?familyid=56E5B1C5-BF17-42E0-A410-371A838E570A
Generate the scripts?
Generate a script to create the table then generate a script to insert the data.
check-out SP_ Genereate_Inserts for generating the data insert script.
Create the database, with Script Database as... CREATE To
Within SSMS on the source server, use the export wizard with the destination server database as the destination.
Source instance > YourDatabase > Tasks > Export data
Data Soure = SQL Server Native Client
Validate/enter Server & Database
Destination = SQL Server Native Client
Validate/enter Server & Database
Follow through wizard

Resources