I frequently create scripts that back up a database on one server and restore it on another server. With sqlcmd you can achieve the whole thing in a single script file because you can connect to both source and destination server. The following script backs up the Northwind database on one server and restores it on another server:
– connect to the source server
:CONNECT rrehak\sql2000
BACKUP DATABASE Northwind
TO DISK = ‘C:\Temp\Northwind.bak’
WITH INIT
GO
– connect to the destination server
:CONNECT rrehak
– if the database exists, disconnect any
possible connections
IF EXISTS (SELECT * FROM
master.dbo.sysdatabases WHERE name =
‘Northwind’)
ALTER DATABASE Northwind
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
RESTORE DATABASE [Northwind]
FROM DISK = N’C:\Temp\Northwind.bak’
WITH FILE = 1,
MOVE N’Northwind’ TO N’C:\SQL Server
Databases\Northwind.mdf’,
MOVE N’Northwind_log’ TO N’C:\SQL Server
Databases\Northwind_1.ldf’,
NOUNLOAD, STATS = 10
GO
Here’s one more improvement to the script above, which demonstrates how to execute operating system commands from sqlcmd. The demo script restored the database from the location where the source database was backed up. Let’s say you want to copy a backup file to a folder on the destination server because you’ll need to restore the file repeatedly and want to avoid restoring over the network. Sqlcmd can execute DOS commands using the :!! directive. In this case, place the following script after the backup section and before the restore section to execute the DOS copy command for creating a copy of the backup file:
:setvar CopyCommand “copy
\ \sqlserver1\c$\Temp\Northwind.bak
\ \sqlserver2\c$\sql”
:!! $(CopyCommand)
All of these features make sqlcmd the tool of choice for automating SQL Server administration and maintenance tasks. For example, you can create a “worker” script file that contains a common set of SQL scripts that need to execute in multiple databases, possibly on multiple servers as well. Inside of that script you would use sqlcmd variables.