SQL Clone
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 

Comparing two SQL instances

Last week I was working on a couple of SQL instances that contained databases which were part of an Always On availability group, with one server being the primary and the other the secondary.

I needed to make sure that the secondary had all the databases that were on the primary (darn you auto seeding!!). The problem was that these instances had over 200 databases which meant checking them was no simple task.

Now I know there’s a few ways to do this but the method I used is a simple & quick way of comparing databases on two SQL instances using the powershell cmdlet

Compare-Object

What this does is pretty much what it says on the tin. The cmdlet takes two objects and compares them based on a input property (in this case it’ll be database names).

Here’s the code: –

$InstanceA = ''
$InstanceB = ''

$SqlQuery = 'SELECT name FROM sys.databases'

$DatabasesA = Invoke-SqlCmd2 -sqlinstance $InstanceA -query $SqlQuery

$DatabasesB = Invoke-SqlCmd2 -SqlInstance $InstanceB -query $SqlQuery

Compare-Object -ReferenceObject $DatabasesA -DifferenceObject $DatabasesB -Property "name"

Let’s run a quick test to show the output. Say I have two SQL instances with the following databases: –

If I run the script, I will get the following: –

This is telling me that Databases C & G exist in Instance B but not Instance A and that Databases E & I exist in Instance A but not in Instance B.

The script runs very quickly (even with a large amount of dbs) and gives a nice, easy to understand output that allowed me to work out which databases needed to be reseeded in my AG.

Of course, the $SqlQuery variable can be changed so that it can return other properties of the instances for comparison so this really is a nice way to compare two SQL instances.

Thanks for reading!

The DBA Who Came In From The Cold

I’m Andrew Pruski and I am a SQL Server DBA with 5 years experience in database development and administration.

The online SQL Server community has helped me out immensely throughout my career, whether from providing reference material in blog posts, or answering my (sometimes obscure) questions on forums. So, to try and say thank you, I would like to contribute my own experiences in the hope that they could benefit someone out there.

So here’s my general ramblings and thoughts about working as a SQL Server DBA.

You can find me on twitter @DBAFromTheCold

If you have any feedback on my blog please send me an email to dbafromthecold@gmail.com.

Comments

Leave a comment on the original post [dbafromthecold.com, opens in a new window]

Loading comments...