bisonn

fn_hadr_group_is_primary

Sep 24th, 2020 (edited)
982
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use master
  2. go
  3. create or alter function dbo.fn_hadr_group_is_primary (@agname sysname) returns bit as
  4. begin
  5.     if exists (select name from sys.availability_groups) begin
  6.         declare @primaryreplica sysname
  7.  
  8.         select
  9.         @primaryreplica = hags.primary_replica
  10.         from sys.dm_hadr_availability_group_states hags
  11.         inner join sys.availability_groups ag on ag.group_id = hags.group_id
  12.         where ag.name = @agname
  13.  
  14.         if upper(@primaryreplica) = upper(@@servername) return 1 -- primary
  15.         else return 0 -- secondary
  16.     end
  17.     return 1 -- not AG server
  18. end
  19. go
RAW Paste Data