FN_HADR_GROUP_IS_PRIMARY function
USE master
go
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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;
---Add this command as first step in any job, so that the job will check
DECLARE @AGState TINYINT;
SELECT @AGState =dbo.fn_hadr_group_is_primary('ContentStore_BAG');
IF @AGState =0
BEGIN
RAISERROR('Secondary node',11, 1);
END
USE master go SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO 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; ---Add this command as first step in any job, so that the job will check DECLARE @AGState TINYINT; SELECT @AGState =dbo.fn_hadr_group_is_primary('ContentStore_BAG'); IF @AGState =0 BEGIN RAISERROR('Secondary node',11, 1); END
Comments