Running sql commands only on primary server in high availability group

28 May 2018

high availability group sql

Running sql commands only on primary server in high availability group

DECLARE @isPrimary bit = 0

IF SERVERPROPERTY ('IsHadrEnabled') = 1
BEGIN
    SELECT
    @isPrimary = 1
    FROM
    sys.availability_groups_cluster AS AGC
    INNER JOIN sys.dm_hadr_availability_replica_cluster_states AS RCS ON RCS.group_id = AGC.group_id
    INNER JOIN sys.dm_hadr_availability_replica_states AS ARS ON ARS.replica_id = RCS.replica_id
    INNER JOIN sys.availability_group_listeners AS AGL ON AGL.group_id = ARS.group_id
    WHERE
        ARS.role_desc = 'PRIMARY' and RCS.replica_server_name = @@SERVERNAME
END
ELSE
BEGIN
    set @isPrimary = 1
END

IF @isPrimary = 1
BEGIN
    -- your script here        
END

Further reading
Finding Primary Replicas for SQL Server 2012 AlwaysOn Availability Groups with PowerShell
@@SERVERNAME
sys.fnhadrisprimaryreplica


Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.