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

Popular posts from this blog

System.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out

Pre login Handshake or Connection Timeout Period

Transparent Data Encryption(TDE) with Master Key and Certificate in SQL Server