Book Image

Getting Started with SQL Server 2014 Administration

By : Gethyn Ellis
Book Image

Getting Started with SQL Server 2014 Administration

By: Gethyn Ellis

Overview of this book

Table of Contents (13 chapters)
Getting Started with SQL Server 2014 Administration
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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...