У вас могут быть задания в обоих экземплярах, в первичной и вторичной репликах, а затем использовать sys.fn_hadr_is_primary_replica
на первом этапе вашей работы.
IF sys.fn_hadr_is_primary_replica ( 'yourDBname' ) <> 1
BEGIN
-- raiserror, so the job step fails and the entire job fails
-- sometimes you may want to set this job to "finish with success" when this step fails
-- so that you don't get alerts
declare @errMsg varchar(600) = 'This is meant to run on the primary replica'
raiserror(@errMsg,16,1)
END
ELSE
BEGIN
print 'This is the primary replica, continue with the job'
END
Это будет работать на 2014+. В 2012 году вы можете проверить некоторые системные представления для первого шага.
IF EXISTS(SELECT
AGC.name -- Availability Group
, RCS.replica_server_name -- SQL cluster node name
, ARS.role_desc -- Replica Role
, AGL.dns_name -- Listener Name
FROM
sys.availability_groups_cluster AS AGC
LEFT JOIN sys.dm_hadr_availability_replica_cluster_states AS RCS
ON RCS.group_id = AGC.group_id
LEFT JOIN sys.dm_hadr_availability_replica_states AS ARS
ON ARS.replica_id = RCS.replica_id
LEFT JOIN sys.availability_group_listeners AS AGL
ON AGL.group_id = ARS.group_id
WHERE
RCS.replica_server_name = @@SERVERNAME
and ARS.role_desc = 'PRIMARY')
BEGIN
print 'Continue with job'
END
ELSE
BEGIN
declare @errMsg varchar(600) = 'This is meant to run on the primary replica'
raiserror(@errMsg,16,1)
END