Blog Post

Multi-server scripts with SSMS using SQLCMD mode

,

SSMS is the most common tool used by SQL Developers or DBA’s but unfortunately there are some features that are barely known, SQLCMD mode is not the exception and that’s why I decided to follow up in this topic.

You may want to check one of this previous blog post, where you will find instructions how to enable SQLCMD mode and some examples that could help you to become familiar with it.

One of my favorite things about SQLCMD mode, is that allows you to connect to multiple servers using the same SSMS editor window. That means, we can run the same T-SQL script on multiple servers one after the other.

All SQLCMD mode commands starts with colon sign (:), in this case what we want to do is to connect to multiple servers so we need to make use of the :CONNECT command.

Imagine you have to backup and restore a database from production to a development environment and because this is an on demand task you want to have a handy script to run it every time needed, let’s give it a try.

-- Connecting to source server, taking full and log backup
:CONNECT Instance1
USE [master]
GO
BACKUP DATABASE [ProdDB] TO DISK=N’\\Instance2\D$\ProdDB.bak’ WITH NOFORMAT, NOINIT,
NAME =N’ProdDB-Full Database Backup’, SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 5
GO
BACKUP LOG [ProdDB] TO DISK=N’\\Instance2\D$\ProdDB.trn’ WITH NOFORMAT, NOINIT,
NAME =N’ProdDB-Log Database Backup’, SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 5
GO
-- Connecting to target server, restoring full and log backup
:CONNECT Instance2
USE [master]
GO
RESTORE DATABASE [DevDB] FROM DISK=N’D:\ProdDB.bak’ WITH FILE=1,
MOVE N’ProdDB_data’ TO ‘E:\DATA\DevDB_data.mdf’,
MOVE N’ProdDB_main_01’ TO ‘F:\DATA\DevDB_main_01.ndf’,
MOVE N’ProdDB_log’ TO ‘G:\DATA\DevDB_log.ldf’,
NORECOVERY, NOUNLOAD, REPLACE, STATS = 5
GO
RESTORE LOG [DevDB] FROM DISK=N’D:\ProdDB.trn’ WITH FILE=1,NORECOVERY, NOUNLOAD, REPLACE, STATS = 5
GO
-- Recovering database
RESTORE DATABASE [DevDB] WITH RECOVERY
GO

As you can see from the example above, just using the :CONNECT functionality in SQLCMD mode allows me to run mixed operations between servers. In this particular example I took a full and log backup of a database, then without leaving my query window (session) on SSMS I connected to the target server and restored both files.

This is just a simple example, you can even run the same script in a large collection of servers to make repetitive admin tasks easier.

Stay tuned for more DBA mastery tips!

The post Multi-server scripts with SSMS using SQLCMD mode appeared first on DBA MASTERY.

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating