T-SQL query to Get Details of AlwaysOn HighAvailability Groups

Here is T-SQL query to Get Details of AlwaysOn HighAvailability Groups.

select * into #myTempag_availability_groups from master.sys.availability_groups
select agstates.group_id, agstates.primary_replica into #myTempag_availability_group_states from master.sys.dm_hadr_availability_group_states as agstates
select group_id, replica_id, replica_metadata_id into #myTempag_availability_replicas from master.sys.availability_replicas
select replica_id, is_local, role into #myTempag_availability_replica_states from master.sys.dm_hadr_availability_replica_states
SELECT
AG.name AS [Name],
'Server[@Name=' + quotename(CAST(
        serverproperty(N'Servername')
       AS sysname),'''') + ']' + '/AvailabilityGroup[@Name=' + quotename(AG.name,'''') + ']' AS [Urn],
ISNULL(agstates.primary_replica, '') AS [PrimaryReplicaServerName],
CASE 
WHEN ISNULL(arstates2.role, 3) = 0 THEN 'RESOLVING'
WHEN ISNULL(arstates2.role, 3) = 1 THEN 'PRIMARY'
WHEN ISNULL(arstates2.role, 3) = 2 THEN 'SECONDARY'
END AS [LocalReplicaRole]
FROM
#myTempag_availability_groups AS AG
LEFT OUTER JOIN #myTempag_availability_group_states as agstates ON AG.group_id = agstates.group_id
INNER JOIN #myTempag_availability_replicas AS AR2 ON AG.group_id = AR2.group_id
INNER JOIN #myTempag_availability_replica_states AS arstates2 ON AR2.replica_id = arstates2.replica_id AND arstates2.is_local = 1
ORDER BY
[Name] ASC
drop table #myTempag_availability_groups
drop table #myTempag_availability_group_states
drop table #myTempag_availability_replicas
drop table #myTempag_availability_replica_states