Reader small image

You're reading from  Getting Started with SQL Server 2014 Administration

Product typeBook
Published inApr 2014
PublisherPackt
ISBN-139781782172413
Edition1st Edition
Right arrow
Author (1)
Gethyn Ellis
Gethyn Ellis
author image
Gethyn Ellis

Gethyn Ellis has over eighteen years of experience with SQL Server and for past ten years he has been working on Azure. He is an Microsoft certified trainer. He also trains and is a consultant for SQL Server. Prior to this he has worked with Packt and written books on "Getting Started SQL Server 2014 Administration" , "Microsoft Azure laaS Essentials", and Professional Azure SQL Database Administration.
Read more about Gethyn Ellis

Right arrow

Troubleshooting Availability Groups


A new system function has been added that will help you identify if the database and instance you are currently working on is the primary replica. The function is called sys.fn_hadr_is_primary_replica and the syntax for the is function is as follows:

sys.fn_hadr_is_primary_replica ( 'dbname' )

Here, 'dbname' is the name of the database you want to check. The procedure returns a 1, if it evaluates to true, that is, it is the primary replica. You can combine this with some logical code to determine which section of the code to run depending on whether the replica is currently the primary replica.

The following script will back up your database if the current instance that it runs is the primary instance:

declare @dbname varchar(30)
declare @backuplocation varchar(80)

set @dbname = 'DB1'
Set @backuplocation = 'c:\BACKUP\'
set @backuplocation = @backuplocation + @dbname
If sys.fn_hadr_is_primary_replica ( @dbname ) <> 1 
begin 
SELECT 'Nothing to backup...
lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Getting Started with SQL Server 2014 Administration
Published in: Apr 2014Publisher: PacktISBN-13: 9781782172413

Author (1)

author image
Gethyn Ellis

Gethyn Ellis has over eighteen years of experience with SQL Server and for past ten years he has been working on Azure. He is an Microsoft certified trainer. He also trains and is a consultant for SQL Server. Prior to this he has worked with Packt and written books on "Getting Started SQL Server 2014 Administration" , "Microsoft Azure laaS Essentials", and Professional Azure SQL Database Administration.
Read more about Gethyn Ellis