May 262020

What happens if you have a SQL Agent job, but the logic is not aware (or cannot be aware) that you may have an Availability Group in place. There is nothing built-in to Agent to account for this, but there is a way can you configure an Agent job to check for the existence of an AG before proceeding.

Here is the scenario.

First, we have a 2-node cluster running a synchronous Availability Group with automatic failover and readable secondaries turned off. Next, we have a requirement to run a SQL Agent job every hour to collect data from a user database. Since the AG is configured for automatic failover, we need to make sure the job will continue to run successfully regardless of which node is active.

With readable secondaries turned off, this creates a problem for any Agent job that needs to read from those user databases. Those jobs will fail with an error saying the database not accessible for queries.

We can easily get around this issue by using a single query and an extra job step.

First, we need to add a TSQL job step that we will call “AG Check” to execute the following query.

IF sys.fn_hadr_is_primary_replica('WSS_Content') <> 1
  THROW 50000, 'This is not the primary replica.', 1;

This query uses a DMF, sys.fn_hadr_is_primary_replica, to determine if a database is a part of the primary or secondary replica. The function will return a value of 1 if we are on the primary replica, so if it returns anything else then we want to throw an error. The error will allow us to change the behavior of the job.

Note: sys.fn_hadr_is_primary_replica was introduced in SQL Server 2014; however, I wrote a function that can do the same thing for SQL Server 2012.

Next, on the Advanced tab, we need to change the On Failure Action to “Quit the job reporting success”, then click OK.

We want to use “Quit the job reporting success” in stead of “Quit the job reporting failure”, so the overall result of the job will be successful. That way we will not cause additional email alerts to be sent.

Finally, on the Steps tab, we need to use the Move arrows to make sure AG Check is the first step on the list, and make sure it is listed as the start step.

The result is we that we now have a job with two steps. The first step checks the status of the replica. If it succeeds, then we can proceed to the next step to do actual work. If the first step fails, then we gracefully exit the job.

There are other ways you can setup an Agent job to account for an Availability group, but this method is quick and easy to setup for almost any environment.

Aug 272013
You’ve spent a lot of time planning and building out a new SQL Server 2012 environment complete with Availability Group Listeners, but how can you be sure the end users are connecting to the listener and not directly to the SQL Server instance?
So why would we care about this?  To begin with, if the users are not connecting to the listener, then upon a failover to another replica, those users would have to connect to a different SQL Server instance name.  Having a single point of connection is crucial for the high availability process to work correctly.
In a previous blog post, we setup an Availability Group Listener,, with two IP addresses: &  We’ll use this one for our example.

The DMV, sys.dm_exec_connections, contains information about each connection to a SQL Server instance, and can be used to answer our question.
Open a TSQL connection to either the Availability Group listener, and execute the following command.

FROM sys.dm_exec_connections;

The local_net_address and local_tcp_port columns will display the IP address and port number of the client’s connection target.  This will be the connection string the users entered to connect to the SQL Server instance.
If the IP address and port number match the Availability Group IP, then you’re in good shape.  If they do not match, then some users are likely connecting directly to the SQL Server instance, and that will need to be changed.
By joining the sys.dm_exec_sessions DMV, you’ll also be able to get the hostname and program name of each connection.

FROM sys.dm_exec_connections ec
JOIN sys.dm_exec_sessions es ON ec.session_id = es.session_id;

As you can see in this picture, we have one connection on session_id 62 that is connecting directly to the SQL Server instance and not the to the Availability Group Listener.  At this point, I would track down that user, and have them use the correct connection string.
Using this DMV will allow you to verify the users are connecting to SQL Server using the correct connection strings, and help prevent unneeded outages during a failover between replicas.

Jul 232013
UPDATED — Jul 3, 2015 — To verify database exists, per comments by Konstantinos Katsoridis. Thanks for finding the bug!

In my recent adventures with AlwaysOn Availability Groups, I noticed a gap in identifying whether or not a database on the current server is the primary or secondary replica.  The gap being Microsoft did not provide a DMO to return this information.  The good news is the documentation for the upcoming release of SQL Server 2014 looks to include a DMO, but that doesn’t help those of us who are running SQL Server 2012.

I’ve developed a function, dbo.fn_hadr_is_primary_replica, to provide you with this functionality.  This is a simple scalar function that takes a database name as the input parameter and outputs one of the following values.
 0 = Resolving
 1 = Primary Replica
 2 = Secondary Replica
-1 = Database Does Not Exist
The return values correspond to the role status listed in sys.dm_hadr_availability_replica_states.
In this example, I have setup 2 SQL Servers (SQLCLU1SPIRIT1 and SQLCLU2SPIRIT2) to participate in some Availability Groups.  I have setup 2 Availability Groups; one for AdventureWorks2012 and a second for the Northwind database.  SQLCLU1SPIRIT1 is the primary for AdventureWorks2012 and secondary for Northwind.  SQLCLU2SPIRIT2 is the primary for Northwind and secondary for AdventureWorks2012.
First let’s run the function for both databases on SQLCLU1SPIRIT1.
On this server, the function returns 1 because it’s the primary for AdventureWorks2012, and returns 2 because it’s the secondary for Northwind.
Now let’s run it again on SQLCLU2SPIRIT2.
As expected we get the opposite result.
This function does not take into account the preferred backup replica; it only returns information based on whether it is the primary or secondary replica.  It was created to use within other scripts to help determine a database’s role if it’s part of an Availability Group.  I hope this script can help you as well.

USE master;

IF OBJECT_ID(N'dbo.fn_hadr_is_primary_replica', N'FN') IS NOT NULL
    DROP FUNCTION dbo.fn_hadr_is_primary_replica;

CREATE FUNCTION dbo.fn_hadr_is_primary_replica (@DatabaseName SYSNAME)

  File Name:    fn_hadr_is_primary_replica.sql

  Applies to:   SQL Server 2012

  Purpose:      To return either 0, 1, 2, or -1 based on whether this 
                @DatabaseName is a primary or secondary replica.

  Parameters:   @DatabaseName - The name of the database to check.

  Returns:      0 = Resolving
                1 = Primary
                2 = Secondary
               -1 = Database does not exist

  Author:       Patrick Keisler

  Version:      1.0.1 - 07/03/2015


  License:      Freeware



    IF EXISTS (SELECT 1 FROM sys.databases WHERE name = @DatabaseName)
        -- Return role status from sys.dm_hadr_availability_replica_states
        SELECT @HadrRole = ars.role
        FROM sys.dm_hadr_availability_replica_states ars
        INNER JOIN sys.databases dbs 
            ON ars.replica_id = dbs.replica_id
        WHERE = @DatabaseName;
        -- @DatabaseName exists but does not belong to an AG so return 1
        IF @HadrRole IS NULL RETURN 1;

        RETURN @HadrRole;
        -- @DatabaseName does not exist so return -1
        RETURN -1;
Jul 162013
Before we get started, I want to make it clear this is NOT how you would normally configure all these items in a production environment.  This is meant for a lab or demo area to play with Availability Groups over multiple subnets.
I use VMware a lot for demos at work as well as tooling around with various Windows and SQL Server related stuff.  In working with Availability Groups, one of the things I would like to do for my demos is have multiple subnets in VMware Workstation, so I can simulate a site failover.
Just to test Availability Groups requires at least three VMs; one for the Active Directory domain controller, one for the primary replica, and one for the secondary replica.  For this demo, we’ll still just need those three VMs.
I’m not going to cover all the steps to setup an Active Directory domain controller or install SQL Server.  I’ll assume you have already completed those steps on each of the VMs.  All three of my VMs are running Windows Server 2008 R2 Enterprise Edition.  If you are running a different version, then some of these screenshots could be different.
Here is the setup for each VM.
  1. Windows Active Directory Domain Controller (MCP domain)
  2. DNS server (
  3. Network Policy and Remote Access (used for routing)
  4. Connected to both 192.168.1.x and 192.168.2.x subnets

  1. SQL Server 2012 Enterprise Edition
  2. SPIRIT1 is the named instance listening on port 1433
  3. Connected to 192.168.1.x subnet

  1. SQL Server 2012 Enterprise Edition
  2. SPIRIT2 is the named instance listening on port 1433
  3. Connected to 192.168.2.x subnet

  1. Availability Group for the AdventureWorks2012 database
  2. Listening on port 1433
  3. Mapped to and

Now that you see how the finished environment is setup, let’s see how to get there.
The first thing we need to do is setup each of the custom networks.   From the VMware Workstation menu, open the Virtual Network Editor.  Click on “Add Network” and select VMnet2.  Select Host-only and uncheck both the “Connect to Host Virtual Adapter” and “Use local DHCP” options.  Set the subnet IP to and the subnet mask to
Click “Add Network” and select VMnet3.  Make all the same setting changes, but this time set the subnet IP to 

On the VM that is your Active Directory Domain Controller (PDC):
Edit the settings of the VM.  Make sure you have only ONE network card, and assign it to VMnet2.

Power on your VM domain controller.  Once it’s up, edit the IPv4 settings of your network card.  Since we’re not using DHCP, we’ll need to hard code the IP address.  I have my domain controller IP set to  You can set yours to any IP as long as it’s on the same subnet.  Set the subnet mask to and then leave the gateway blank.  Set the preferred DNS server to, because this is also your DNS server.  Save the changes and then shutdown the VM.
Edit the settings if the VM, add a 2nd network card and assign it to VMnet3. 

Power on the VM.  Once it’s up, edit the IPv4 settings of the new network card.  This time set the IP to, the subnet mask to, and the Preferred DNS server to Save the changes.
Your PDC will act as a router between the two subnets, but it will need software to make it happen.  Open Server Manager, select roles, and then “Add Role”.  Select “Network Policy and Access Services”.
For the service role, select “Routing”.  It will automatically select the other required services.
Click next and then install. Once the installation is complete, go to Administrative Tools and open “Routing and Remote Access”.  Right click on the domain controller and select “Configure and Enable Routing and Remote Access”.   From the wizard, choose “Custom Configuration” then click Next.  Select “LAN Routing” then click next to complete the configuration. 
When a pop up asks to start the service, click “Start Service”.  Once the configuraiton is complete, you now have software routing enabled on your domain controller.  The routing should be automatically configured between the two subnets. 
You would normally use a hardware router for this job, but the Routing and Remote Access service functions just fine for a lab running on VMware.  The next step is to configure the network and IP settings for each of our SQL Servers. 

On the first SQL Server VM (SQLCLU1):
Open the VM properties and make sure your network card is assigned to VMnet2. 

Save the settings and then power on the VM.  Once it’s up, edit the IPv4 settings of the network card.  Set the IP address to  Set the subnet mask to and the default gateway to  The default gateway needs to be the IP address of the server that is running the Routing and Remote Access service.  In this case, it’s the IP of the domain controller.  Set the Preferred DNS server to  Click OK to save the settings.
Additionally, you will need to open firewall ports TCP 5022 for the HADR service, TCP 1433 for the SQL Server service, and UDP 1434 for the SQL Server Browser service.

On the second SQL Server VM (SQLCLU2):
Open the VM properties and make sure your network card is assigned to VMnet3. 

Save the settings and then power on the VM.  Once it’s up, edit the IPv4 settings of the network card.  Set the IP address to  Set the subnet mask to and the default gateway to  The default gateway needs to be the IP of the 2nd network care we setup earlier on the domain controller.  Set the Preferred DNS server to  Click OK to save the settings.
Additionally, you will need to open firewall ports TCP 5022 for the HADR service, TCP 1433 for the SQL Server service, and UDP 1434 for the SQL Server Browser service.

Your two subnets should be working now.  If you want to test it, just open a command prompt from SQLCLU1 and issue a “PING SQLCLU2”.  You can do the same test from SQLCLU2.

Setting up the Windows Cluster
Open Failover Cluster Manager and click “Create a Cluster”.  Step through the setup wizard by selecting the two cluster nodes: SQLCLU1 and SQLCLU2. 
Key in the name of the cluster, SQLCLUV1.  Select the subnet and enter the IP address of  Make sure to uncheck the other subnet.  Click next to finish the setup.
At this point we would normally configure the quorum; however, since this is just for a lab setup, we’ll leave the quorum set to Node Majority.  When setting this up in a production environment, you’ll want to configure the quorum based on the number voting nodes.  This link will guide you through what changes are needed.
Look at the settings of each of the cluster networks.  Cluster Network 1 is the 192.168.1.x subnet and is connected to SQLCLU1. 
Cluster Network2 is the 192.168.2.x subnet and is connect to SQLCLU2.
Setting up the Availability Group
Now comes the easy part.  First we’ll need to enable the Availability Group feature on each SQL Server instance.  On SQLCLU1, open the SQL Server Configuration Manger.  Right click on the SQL Server service and select properties.  Select the “AlwaysOn High Availability” tab, and check the box to enable it.  Click OK to save the changes, and then stop and restart the SQL Service services. 
Make the change on the second SQL Server, SQLCLU2.
Now make sure the AdventureWorks2012 database is in FULL recovery mode.  Within SQL Server Management Studio we’ll setup the Availability Group for the AdventureWorks2012 database.  Open Object Explorer to SQLCLU1SPIRIT1. Right click on the “AlwaysOn High Availability” node and select “New Availability Group Wizard”.  Enter a name for the group, AdventureWorks2012AG and click next.
Check the box next to the AdventureWorks2012 database and click next.
Click Add Replica and add SQLCLU2SPIRT2 to the list of replicas.  Check all the boxes for Automatic Failover and Synchronous Commit.
Click the Listener tab.  Select the “Create an Availability Group Listner” radio button, then enter a listener name and port number and make sure Static IP is selected for Network Mode.
Click the Add button.  Select the subnet and enter the IP of the listener,, then click OK.
Click the Add button again.  Select the subnet and enter the second IP of the listener,, then click OK.  You should now see 2 separate IP address for the listener.  Click Next to continue.
Select FULL data synchronization and specify a backup file share, \SQLCLU1BACKUP, and click next.  The file share is only needed to complete the initial data synchronization.
Verify all the validation checks are successful and then click next.  Click finish to complete the Availability Group setup.
Once the setup is complete, go back into Failover Cluster Manager to check out the Availability Group resource that was added.  What you’ll notice is two IP addresses associated to the Availability Group listener.  One is currently online and the other is offline.  The IP that’s online is associated to the subnet that SQLCLU1 is on, because it’s currently the primary replica.
Now let’s failover the Availability Group to SQLCLU2SPIRIT2 to see what happens to the listener.  Open a query window to SQLCLU2SPIRIT2 and run the following code.
Once the failover is complete, go back into Failover Cluster Manager to check out the properties of the Availability Group.  You’ll notice the IP resources have switched.  The IP is offline and is online.
SQLCLU2SPIRIT2 is now the primary replica for the Availability Group and it’s on the 192.168.2.x subnet.  You can also go back to the domain controller and open up the DNS Manager.  There you will see the two DNS entries for the the Availability Group listener; one for each IP address.
What we’ve covered here is a quick and easy way to setup an Availability Group on multiple subnets within VMware Workstation.  Remember this is not how you would normally setup everything within a production environment.  In a production environment we’d use a hardware router instead of the routing service, the separate subnets would likely be in different data centers, and the quorum would be configured according the number voting nodes.  However, this provides you with a platform for doing multisubnet failovers with Availability Groups.