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.
1 = Primary Replica
2 = Secondary Replica
-1 = Database Does Not Exist
USE master;
GO
IF OBJECT_ID(N'dbo.fn_hadr_is_primary_replica', N'FN') IS NOT NULL
DROP FUNCTION dbo.fn_hadr_is_primary_replica;
GO
CREATE FUNCTION dbo.fn_hadr_is_primary_replica (@DatabaseName SYSNAME)
RETURNS TINYINT
WITH EXECUTE AS CALLER
AS
/********************************************************************
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
Help: http://www.patrickkeisler.com/
License: Freeware
********************************************************************/
BEGIN
DECLARE @HadrRole TINYINT;
IF EXISTS (SELECT 1 FROM sys.databases WHERE name = @DatabaseName)
BEGIN
-- 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 dbs.name = @DatabaseName;
-- @DatabaseName exists but does not belong to an AG so return 1
IF @HadrRole IS NULL RETURN 1;
RETURN @HadrRole;
END
ELSE
BEGIN
-- @DatabaseName does not exist so return -1
RETURN -1;
END
END;
GO