Sql-server – Clarification — Disabling SQL Server 2014 Agent Job in AOAG Secondary replicas

availability-groupssql server 2014sql-server-agent

We have AGs set up (1 primary and 2 secondaries (Includes DR)).

We have an archival job set up in each replica with same schedule and enabled in all three replicas.

This job runs in a frequency of about 15 minutes each day.

My question is:

Since the job in each replica is pointed to primary server while running :

  1. Can I let the job run only in Primary Replica and disable the Job in secondary replicas ? Will it affect otherwise ?

  2. In AlwaysOn AGs will the jobs also be failed over ?

  3. If jobs not failover

My thinking is once the primary is failed over to other node (which is would be primary or current secondary synchronized) and since the secondary replica is now primary and the job will be in disabled state (If at all we can disable the jobs in secondary ?), I just need to enable it on the current replica.

Kindly correct my thinking ?

Regards

Best Answer

just need to enable it on the current replica.

You will need to modify you sql agent jobs to include below step

CREATE FUNCTION dbo.fn_hadr_group_is_primary (@AGName sysname)
RETURNS bit 
AS
BEGIN 
DECLARE @PrimaryReplica sysname; 
SELECT @PrimaryReplica = hags.primary_replica 
FROM 
sys.dm_hadr_availability_group_states hags
INNER JOIN sys.availability_groups ag ON ag.group_id = hags.group_id
WHERE
ag.name = @AGName;

IF UPPER(@PrimaryReplica) =  UPPER(@@SERVERNAME)
RETURN 1; -- primary

RETURN 0; -- not primary
  END; 

GO

So you have to create the above function in all your replicas and add as first step in sql agent jobs you wish to execute

If the replica is not primary,you can modify the job to Quit

This has been covered in depth here :
AlwaysOn Availability Groups and SQL Server Jobs, Part 7: Detecting Primary Replica Ownership