Ads

09 February 2018

SSRS Key Mangement Options

C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn>RSKeyMgmt /?
Microsoft (R) Reporting Services Key Manager
Version 11.0.2100.60 x86

Performs key management operations on a local report server.

  -e  extract           Extracts a key from a report server instance
  -a  apply             Applies a key to a report server instance
  -s  reencrypt         Generates a new key and reencrypts all encrypted
                        content
  -d  delete content    Deletes all encrypted content from a report server
                        database
  -l  list              Lists the report servers announced in the report server
                        database
  -r  installation ID   Remove the key for the specified installation ID
  -j  join              Join a remote instance of report server to the
                        scale-out deployment of the local instance
  -i  instance          Server instance to which operation is applied;
                        default is MSSQLSERVER
  -f  file              Full path and file name to read/write key.
  -p  password          Password used to encrypt or decrypt key.
  -m  machine name      Name of the remote machine to join to the
                        scale-out deployment
  -n  instance name     Name of the remote machine instance to join to the
                        scale-out deployment
  -u  user name         User name of an administrator on the machine to join to
                        the scale-out deployment.  If not supplied, the current
                        user is used.
  -v  password          Password of an administrator on the machine to join to
                        the scale-out deployment
  -t  trace             Include trace information in error message

To create a back-up copy of the report server encryption key:
RSKeyMgmt -e [-i <instance name>] -f  -p 

To restore a back-up copy of the report server encryption key:
RSKeyMgmt -a [-i <instance name>] -f  -p 

To reencrypt secure information using a new key:
RSKeyMgmt -s [-i <instance name>]

To reset the report server encryption key and delete all encrypted content:
RSKeyMgmt -d [-i <instance name>]

To list the announced report servers in the report server database:
RSKeyMgmt -l [-i <instance name>]

To remove a specific installation from a scale-out deployment:
RSKeyMgmt -r <installation ID> [-i <instance name>]

To join a remote machine to the same scale-out deployment as the local machine:
RSKeyMgmt -j [-i <local instance name>] -m <remote machine name>
          [-n <remote instance name>] [-u <user name> -v ]

12 January 2018

SQL Server Cluster Uninstall Failed- rule instance removal failed

We recently faced this issue, as the server was migrated to virtual and accidentally windows cluster was removed as part of decommission. Box is left out with SQL Server Installation while uninstalling we hit the below error, once the node name was removed it went successful.




Resolution:

1. Remove the entry from regedit.

HKLM\Software\Microsoft\Microsoft SQL Server\MSSQL11.MSSQLSERVER\Cluster:ClusterName

2. Re-run the uninstall from control panel.


09 January 2018

The EXECUTE permission was denied on the object 'xp_regread', database 'mssqlsystemresource', schema 'sys'.



Receiving 'xp_regread' error as soon as connected to SQL Server Management Studio.
OR

Execution of SSIS packages from SQL jobs fails with error: The EXECUTE permission was denied on the object 'xp_regread', database 'mssqlsystemresource', schema 'sys'




Solution:

To connect and to view the SQL Server Agent:

USE [master]
GO
GRANT EXECUTE ON xp_regread TO [public]
GO


To Execute Job:


-->
USE [master]
GO
GRANT EXECUTE ON xp_sqlagent_enum_jobs TO [public]
GO



20 December 2017

Expanding VM HDD Size - Oracle VM Box

1. Open the command Prompt
2. CD C:\Program Files\Oracle\VirtualBox
3. VBoxmanage modifyhd D:\Linux\Windows\Wind.vhd --resize 30000
4. Exit from command prompt
5. Boot the VM and expand the HDD

26 September 2017

How To Automate SQL Server Trace

How to automate SQL Server Trace:
============================
  • Start SQL Profiler and select File > New Trace. Specify the events, columns, and filters you want in your trace.
  • Start the trace and then stop it.
  • Export the definition. Click File > Export > Script Trace Definition > For SQL Server 2005. ...
  • Save the trace file.
  • Open the file and create a stored procedure.
  • Add below lines to sp to create trace with date and time
 declare @TrcFileName nvarchar(300) 

set @TrcFileName = N'C:\STARTTrace'+CAST(DATEPART(d,GETDATE()) AS varchar(2))+
CAST(DATEPART(M,GETDATE()) AS varchar(2))+CAST(DATEPART(YYYY,GETDATE()) AS varchar(4))
+CAST(DATEPART(HH,GETDATE()) AS varchar(2))+CAST(DATEPART(MI,GETDATE()) AS varchar(2)) 

exec @rc = sp_trace_create @TraceID output, 0, @TrcFileName, @maxfilesize, NULL 
  • To make SP to start when sql server restarts:
USE MASTER
GO
EXEC SP_PROCOPTION SPNAME, 'STARTUP', 'ON'
GO
  • To check SP which are running at start up:
SELECT ROUTINE_NAME
FROM MASTER.INFORMATION_SCHEMA.ROUTINES
WHERE OBJECTPROPERTY(OBJECT_ID(ROUTINE_NAME),'ExecIsStartup') = 1

--see if trace is running

select * from sys.traces
--Mark Trace Store Proc startup option True
EXEC sp_procoption 'StoreProcName', 'startup', 'true';
--Verify start option value is 1
USE MASTER
GO
SELECT VALUE, VALUE_IN_USE, DESCRIPTION
FROM SYS.CONFIGURATIONS
WHERE NAME = 'scan for startup procs'
GO


Msg 19069, Level 16, State 1, Procedure sp_trace_create, Line 1 The trace file name is not valid because it contains a rollover file number (NNN in C:\file_NNN) while the trace rollover option is enabled.

In this case remove the _ (underscore) at the end of the filename.

To rollover files manually use 2 as a parameter in the script.


Lot of thanks to sources :
http://www.techbrothersit.com/search?q=sql+server+profiler
https://dbamohsin.wordpress.com/tag/file-rollover/



22 September 2017

SQL Server 2005 - Insufficient memory or maximum allowed connections


Error:
The client was unable to establish a connection because of an error during connection initialization process before login. Possible causes include the following: the client tried to connect to an unsupported version of SQL Server; the server was too busy to accept new connections; or there was a resource limitation (insufficient memory or maximum allowed connections) on the server. (provider: Named Pipes Provider, error: 0 - No process is on the other end of the pipe.)
Solution:
SQL Services was in hung state and it was not allowing any connections to SQL Server
Restarted SQL Server Instance and issue resolved.

14 August 2017

SSRS Email Subscription Option Missing

SSRS EMAIL SUBSCRIPTION OPTION 


If there is no EMAIL subscription option for the report:

1. Go to SSRS Report services Configuration
2. Choose EMAIL Settings


3. Configure and click Apply.
4. Now go back to report and check subscriptions.





28 July 2017

Move System Databases

Here is the steps to move the system databases:
==================================
Master 

- Change the physical location of the files from startup parameters once the SQL Server is offline, then copy and move the MDF and LDF to new location.
- Now rename existing files as old on previous location
-Now bring SQL Server online

MSDB

SELECT name, physical_name FROM sys.master_files WHERE database_id = DB_ID('msdb');
GO

USE master;
GO
ALTER DATABASE msdb
MODIFY FILE (NAME = MSDBData, FILENAME = 'Z:\Data\MSDBData.mdf');
GO
ALTER DATABASE msdb
MODIFY FILE (NAME = MSDBLog, FILENAME = 'Z:\Log\MSDBLog.ldf');
GO

Model

SELECT name, physical_name FROM sys.master_files WHERE database_id = DB_ID(N'model');
GO

USE master;
GO
ALTER DATABASE model
MODIFY FILE (NAME = modeldev, FILENAME = 'Z:\Data\model.mdf');
GO
ALTER DATABASE model
MODIFY FILE (NAME = modellog, FILENAME = 'Z:\SystemDBs\Log\modellog.ldf');
GO

TEMPDB

Use master
GO
SELECT name AS [LogicalName] ,physical_name AS [Location] ,state_desc AS [Status]
FROM sys.master_files WHERE database_id = DB_ID(N'tempdb');
GO

 USE master;
GO
ALTER DATABASE tempdb
MODIFY FILE (NAME = tempdev, FILENAME = 'Z:\TempDB\Data\tempdb.mdf');
GO
ALTER DATABASE tempdb
MODIFY FILE (NAME = tempdb2, FILENAME = 'Z:\TempDB\Data\TempDB2.ndf');
GO
ALTER DATABASE tempdb
MODIFY FILE (NAME = tempdb3, FILENAME = 'Z:\TempDB\Data\TempDB3.ndf');
GO
ALTER DATABASE tempdb
MODIFY FILE (NAME = tempdb4, FILENAME = 'Z:\TempDB\Data\TempDB4.ndf');
GO
ALTER DATABASE tempdb
MODIFY FILE (NAME = templog, FILENAME = 'Z:\TempDB\Log\templog.ldf');
GO


Resource  DB 

Can I change the Resource database path? Should I?
No

Thanks to :
https://blogs.msdn.microsoft.com/vsanil/2012/11/02/resource-database-common-questions/
https://sqlandme.com/2013/07/08/sql-server-how-to-change-sql-server-errorlog-location/

25 May 2017

Unable to open the physical file , operating system error 5. (Access is denied)

Solution:

1. Add permissions to the disk contain Data and Log files
2. Add service account to login with SA
3. Take DB offline
    Alter database DB_NAME set offline with rollback immediate
4. Bring back the DB online
    Alter database DB_NAME set online with rollback immediate

this resolves the issue, else we need to try restarting SQL Services. Worst-case we need to restore the database with latest backup.

18 April 2017

SQL 2016 - A severe error occurred on the current command. SQL Server Error Log / SQL Services Not coming online



The SQL Server Error log fails with the below error:

A severe error occurred on the current command.  The results, if any, should be discarded. (Microsoft SQL Server, Error: 0)





Solution 1: Repair SSMS tools of SQL Server 2016.
Solution 2: Repair the SQL Server Instance.
Solution 3: Create alias under SQL Server network configuration.

 =======================================================================

Solution 3 will be more appropriate when we see the below error in windows event viewer along with the above mentioned error.

Severity: 16 Error:-1, OS: -1 [Microsoft][ODBC Driver 13 for SQL Server]SQL Server Network Interfaces: Error Locating Server/Instance Specified [xFFFFFFFF].

Solution:




04 March 2017

Maximum Worker Thread


About Worker Thread:

When a request is received, SQL Server will try to locate an idle thread to schedule the request. If an idle worker was not located, new worker will be created. If all workers have been created and none is idle, then the request is queued which will be picked up by any worker thread from the pool of worker threads created.


The following table shows the automatically configured number of max worker threads for various combinations of CPUs and versions of SQL Server.


CPU CORE COUNT
MWT- 32 BIT
MWT-64 BIT 
Up-to 4 processors
256
512
Octa-Core 8 processors
288
576
16 processors
352
704
32 processors
480
960
64 processors
736
1472
128 processors
4224
4480
256 processors
8320
8576


-- show Max number of worker threads on the SERVER
select serverproperty('instancename') as instancename, max_workers_count  as 'AllowedOn64Bit' from sys.dm_os_sys_info 

-- show number Current no of worker threads
select serverproperty('instancename') as instancename, COUNT(*) as MAXCOUNT  from sys.dm_os_workers

-- show the THREADPOOL wait time
select * from sys.dm_os_wait_stats where wait_type = 'THREADPOOL'

---- most of the sessions are waiting for LCK_M_S
select * from sys.dm_os_waiting_tasks

03 March 2017

SQL Server 2000 - the application failed to start because msvcr71.dll or msvcp71.dll was not found

Error:The application failed to start because msvcr71.dll or  msvcp71.dll  was not found  

These files must be present on C:|Windows\System32 folder and also they should be present on SQL\Binn folder, either any software installation/upgrade /Anti virus might bombed these files.

Solution:

1. Search these files on the computer.
2. Paste them to SQL Binaries folder  - C:\Pf\MS\MSSQL\Binn
3. Paste them to C:\Windows\System32 folder also
4. Bring SQL Services online

Hope it helps someone! Thanks.

SQL Server Agent can't Connect-Comes Online - 2016

ERROR: SQLServerAgent could not be started (reason: Unable to connect to server 'WIN\Group'; SQLServerAgent cannot start).


Solution:

1. Connect to SQL Server Instance
2. Go to SQl Server Agent
3. Select -> right Click -> properties -> choose Connection
4. paste instance name as follows
    servername.domain.biz\instance_name
5. Click ok 

Now go to failover cluster manager and bring agent online. Issue resolved.


20 January 2017

Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

Error:

OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "Unspecified error".
Msg 7303, Level 16, State 1, Line 1
Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".


Solution:

There are several solutions on this, but for us the below solution worked great.

Step 1:

sp_configure 'show advanced options', 1;
RECONFIGURE;
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO
Step 2:

USE [master]
GO


EXEC master . dbo. sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'AllowInProcess' , 1
GO

EXEC master . dbo. sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'DynamicParameters' , 1
GO
Step 3:

Full permissions on C:\Users\MSSQLSERVER\AppData\Local\Temp and C:Windows\ServiceProfiles\NetworkService\AppData\Local  for windows nt groups

Thanks to:

http://stackoverflow.com/questions/26267224/the-ole-db-provider-microsoft-ace-oledb-12-0-for-linked-server-null




26 September 2016

Your account information could not be verified - SQL Server 2005 - SP4

ERROR:

"your account information could not be verified. Press OK to return to Authentication Mode screen to determine reason for failure.For setup to verify your credentials the services must be startable,connectable,and you must be a SQL Server Administrator"



Solution:

1) Go to the active node where SQL Server 2005 is running
2) Run the setup from CMD, SQLServer2005SP4-KBXXXXXXX-x86-ENU.exe /passive 
3) Repeat same on all nodes.

10 August 2016

Reporting Services - Unable to Connect to Remote Server Error


This issue occurs due to the values mismatch in the RSWebApplication.config

Go to path :

C:\Program Files\Microsoft SQL Server\\Reporting Services\ReportServer

Edit the above mentioned file.

Add these 2 values:

1. http://Server/ReportServer/
 2. Change the value for SecureConnectionLevel to 0 

Issue resolved!!!

Script To Find Disk and Mount Point Details

11 June 2016

Time For Excel -An error occurred when sending commands to the program


Error Screen:



Two entries in the registry solves the issue

Solution:

1. Go to HKEY_CLASSES_ROOT\Excel.Sheet.8\shell\Open\command
2. Double click default
3. Change value from
"C:\Program Files (x86)\Microsoft Office\Office15\EXCEL.EXE" /dde
to
"C:\Program Files (x86)\Microsoft Office\Office15\EXCEL.EXE" /e "%1"

Repeat the above for Excel.Sheet.12 

Thanks:
https://www.youtube.com/watch?v=xhtRoIP33H0
https://support.microsoft.com/en-in/kb/3001579

05 May 2016

The server network address “TCP://SQLServer:5022” can not be reached or does not exist.

Thanks to Pinal Dave:
Fix/WorkAround/Solution: Try all the suggestions one by one.
Suggestion 1: Make sure that on Mirror Server the database is restored with NO RECOVERY option (This is the most common problem).
Suggestion 2: Make sure that from Principal the latest LOG backup is restored to mirror server. (Attempt this one more time even though the full backup has been restored recently).
Suggestion 3: Check if you can telnet to your ports using command TELNET ServerName Ports like “telnet SQLServerName 5023”.
Suggestion 4: Make sure your firewall is turned off.
Suggestion 5: Verify that the endpoints are started on the partners by using the state or state_desc column the of the sys.database_mirroring_endpoints catalog view. You can start end point by executing an ALTER ENDPOINT statement.
Suggestion 6: Try the following command as one of the last options.
GRANT CONNECT ON ENDPOINT::Mirroring TO ALL
Suggestion 7: Delete the end points and recreate them.


09 March 2016

SP4 on SQL Server 2005 Fails_your account Information could not be verified



SP4 on SQL Server 2005 Fails 



  1. On the active node, use failover cluster manager to pause all passive nodes
  2. On the active node, run and complete the SQL 2005 SP4 installation
  3. On the active node, use failover cluster manager to resume all previously paused nodes
  4. On all passive nodes, run and complete the SQL 2005 SP4 installation using the /passive command line switch
  5. Reboot all node
This will ensue that any necessary system databases are updated as well, as opposed to only the binaries. This can be verified using the sql code below:
SELECT SERVERPROPERTY('productversion') as [SQL Version],
SERVERPROPERTY('productlevel') as [level],
SERVERPROPERTY('edition') as edition,
SERVERPROPERTY('resourceversion') as [Resource Version]



03 February 2016

Change SQL Server Collation @ Instance Level

To change the collation at the instance level we need to follow below steps:

1. Go to Setup.exe path, this will be normally as follows:
     C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\

2. Take the SQL Services Offline.

3.  Go to command prompt and choose above location:

setup /ACTION=REBUILDDATABASE /QUIET /INSTANCENAME= (INSTANCE NAME) /SQLSYSADMINACCOUNTS= (SVC ACC) /SAPWD=(SAPWD) /SQLCOLLATION=SQL_Latin1_General_CP850_BIN 

Instance name:

To verify the instance name  use below query
select SERVERPROPERTY('instancename')

SVC Acc:

Use service account or any domain account which has full permissions on email.

SAPwd:

If its a mixed authentication mode then we need to use SA pwd to complete the rebuild.

4. Check the summary log once its completed for verification, we can verify under instance properties also.

Imp Note: Please take system db backups to restore once we complete rebuild. Else we will loose all SQL Server jobs and Logins. 

04 November 2015

Availability Groups SQL Querys

SQL instance is part of Availability Groups details...
=======================================
SELECT
AG.name AS [AG_Group_Name],
ISNULL(agstates.primary_replica, '') AS [PrimaryReplicaServerName],
ISNULL(arstates.role, 3) AS [LocalReplicaRole]
FROM master.sys.availability_groups AS AG
LEFT OUTER JOIN master.sys.dm_hadr_availability_group_states as agstates
    ON AG.group_id = agstates.group_id
INNER JOIN master.sys.availability_replicas AS AR
    ON AG.group_id = AR.group_id
INNER JOIN master.sys.dm_hadr_availability_replica_states AS arstates
    ON AR.replica_id = arstates.replica_id AND arstates.is_local = 1
ORDER BY [Name] ASC


To get some information about the databases in the Availability Group:
=======================================================
SELECT
AG.name AS [AvailabilityGroupName],
ISNULL(agstates.primary_replica, '') AS [PrimaryReplicaServerName],
ISNULL(arstates.role, 3) AS [LocalReplicaRole],
dbcs.database_name AS [DatabaseName],
ISNULL(dbrs.synchronization_state, 0) AS [SynchronizationState],
ISNULL(dbrs.is_suspended, 0) AS [IsSuspended],
ISNULL(dbcs.is_database_joined, 0) AS [IsJoined]
FROM master.sys.availability_groups AS AG
LEFT OUTER JOIN master.sys.dm_hadr_availability_group_states as agstates
   ON AG.group_id = agstates.group_id
INNER JOIN master.sys.availability_replicas AS AR
   ON AG.group_id = AR.group_id
INNER JOIN master.sys.dm_hadr_availability_replica_states AS arstates
   ON AR.replica_id = arstates.replica_id AND arstates.is_local = 1
INNER JOIN master.sys.dm_hadr_database_replica_cluster_states AS dbcs
   ON arstates.replica_id = dbcs.replica_id
LEFT OUTER JOIN master.sys.dm_hadr_database_replica_states AS dbrs
   ON dbcs.replica_id = dbrs.replica_id AND dbcs.group_database_id = dbrs.group_database_id
ORDER BY AG.name ASC, dbcs.database_name

List of databases that are secondary in the Availability Group,  to be excluded when writes are required
================================================================================
SELECT DISTINCT
dbcs.database_name AS [DatabaseName]
FROM master.sys.availability_groups AS AG
LEFT OUTER JOIN master.sys.dm_hadr_availability_group_states as agstates
   ON AG.group_id = agstates.group_id
INNER JOIN master.sys.availability_replicas AS AR
   ON AG.group_id = AR.group_id
INNER JOIN master.sys.dm_hadr_availability_replica_states AS arstates
   ON AR.replica_id = arstates.replica_id AND arstates.is_local = 1
INNER JOIN master.sys.dm_hadr_database_replica_cluster_states AS dbcs
   ON arstates.replica_id = dbcs.replica_id
LEFT OUTER JOIN master.sys.dm_hadr_database_replica_states AS dbrs
   ON dbcs.replica_id = dbrs.replica_id AND dbcs.group_database_id = dbrs.group_database_id
WHERE ISNULL(arstates.role, 3) = 2 AND ISNULL(dbcs.is_database_joined, 0) = 1
ORDER BY  dbcs.database_name

Monitoring AGs in WSFC Cluster
==========================
select * from sys.dm_hadr_cluster

select * from sys.dm_hadr_cluster_members

select * from sys.dm_hadr_cluster_networks

select * from sys.dm_hadr_instance_node_map

select * from sys.dm_hadr_name_id_map

Monitoring AGs
============
select * from sys.availability_groups

select * from sys.availability_groups_cluster

select * from sys.dm_hadr_availability_group_states

monitoring availability replicas

select * from sys.availability_replicas

select * from sys.availability_read_only_routing_lists

select * from sys.dm_hadr_availability_replica_cluster_nodes

select * from sys.dm_hadr_availability_replica_cluster_states

select * from sys.dm_hadr_availability_replica_states

select  sys.fn_hadr_backup_is_preferred_replica ('DBNAME') -- Used to determine if the current replica is the preferred backup replica.

Monitoring Availability databases :-
==============================
select * from sys.availability_databases_cluster

select * from sys.databases

select * from sys.dm_hadr_auto_page_repair

select * from sys.dm_hadr_database_replica_states

select * from sys.dm_hadr_database_replica_cluster_states

monitor the availability group listeners
=================================

select * from sys.availability_group_listener_ip_addresses

select * from sys.availability_group_listeners

select * from sys.dm_tcp_listener_states

Please refer the below queries for AlwaysOn Availability Groups monitoring reference:

    SERVERPROPERTY (Transact-SQL)

    sys.availability_group_listener_ip_addresses (Transact-SQL)

    sys.availability_group_listeners (Transact-SQL)

    sys.availability_databases_cluster (Transact-SQL)

    sys.availability_groups (Transact-SQL)

    sys.availability_read_only_routing_lists (Transact-SQL)

    sys.availability_replicas (Transact-SQL)

    sys.dm_hadr_availability_replica_cluster_nodes (Transact-SQL)

    sys.dm_hadr_availability_replica_cluster_states (Transact-SQL)

    sys.database_mirroring_endpoints (Transact-SQL)

    sys.dm_hadr_auto_page_repair (Transact-SQL)

    sys.dm_hadr_availability_group_states (Transact-SQL)

    sys.dm_hadr_availability_replica_cluster_states (Transact-SQL)

    sys.dm_hadr_availability_replica_states (Transact-SQL)

    sys.dm_hadr_database_replica_states (Transact-SQL)

    sys.dm_hadr_database_replica_cluster_states (Transact-SQL)

    sys.dm_hadr_cluster (Transact-SQL)

    sys.dm_hadr_cluster_members (Transact-SQL)

    sys.dm_hadr_cluster_networks (Transact-SQL)

    sys.dm_hadr_database_replica_cluster_states (Transact-SQL)

    sys.dm_hadr_database_replica_states (Transact-SQL)

    sys.dm_hadr_instance_node_map (Transact-SQL)

    sys.dm_hadr_name_id_map (Transact-SQL)

    sys.dm_os_performance_counters (Transact-SQL)

    sys.dm_tcp_listener_states (Transact-SQL)

    sys.fn_hadr_backup_is_preferred_replica (Transact-SQL)

MSDN Reference :- https://msdn.microsoft.com/en-nz/library/ff878305.aspx
==============
AlwaysON Dashboard :- http://www.sqlskills.com/blogs/joe/answering-questions-with-the-alwayson-dashboard/
=================

Tempdb Configuration in SQL Server 2016

19 October 2015

Always ON Query's

SQL instance is part of Availability Groups details:

SELECT
AG.name AS [AG_Group_Name],
ISNULL(agstates.primary_replica, '') AS [PrimaryReplicaServerName],
ISNULL(arstates.role, 3) AS [LocalReplicaRole]
FROM master.sys.availability_groups AS AG
LEFT OUTER JOIN master.sys.dm_hadr_availability_group_states as agstates
    ON AG.group_id = agstates.group_id
INNER JOIN master.sys.availability_replicas AS AR
    ON AG.group_id = AR.group_id
INNER JOIN master.sys.dm_hadr_availability_replica_states AS arstates
    ON AR.replica_id = arstates.replica_id AND arstates.is_local = 1
ORDER BY [Name] ASC


To get some information about the databases in the Availability Group:

SELECT
AG.name AS [AvailabilityGroupName],
ISNULL(agstates.primary_replica, '') AS [PrimaryReplicaServerName],
ISNULL(arstates.role, 3) AS [LocalReplicaRole],
dbcs.database_name AS [DatabaseName],
ISNULL(dbrs.synchronization_state, 0) AS [SynchronizationState],
ISNULL(dbrs.is_suspended, 0) AS [IsSuspended],
ISNULL(dbcs.is_database_joined, 0) AS [IsJoined]
FROM master.sys.availability_groups AS AG
LEFT OUTER JOIN master.sys.dm_hadr_availability_group_states as agstates
   ON AG.group_id = agstates.group_id
INNER JOIN master.sys.availability_replicas AS AR
   ON AG.group_id = AR.group_id
INNER JOIN master.sys.dm_hadr_availability_replica_states AS arstates
   ON AR.replica_id = arstates.replica_id AND arstates.is_local = 1
INNER JOIN master.sys.dm_hadr_database_replica_cluster_states AS dbcs
   ON arstates.replica_id = dbcs.replica_id
LEFT OUTER JOIN master.sys.dm_hadr_database_replica_states AS dbrs
   ON dbcs.replica_id = dbrs.replica_id AND dbcs.group_database_id = dbrs.group_database_id
ORDER BY AG.name ASC, dbcs.database_name

List of databases that are secondary in the Availability Group,  to be excluded when writes are required:

SELECT DISTINCT
dbcs.database_name AS [DatabaseName]
FROM master.sys.availability_groups AS AG
LEFT OUTER JOIN master.sys.dm_hadr_availability_group_states as agstates
   ON AG.group_id = agstates.group_id
INNER JOIN master.sys.availability_replicas AS AR
   ON AG.group_id = AR.group_id
INNER JOIN master.sys.dm_hadr_availability_replica_states AS arstates
   ON AR.replica_id = arstates.replica_id AND arstates.is_local = 1
INNER JOIN master.sys.dm_hadr_database_replica_cluster_states AS dbcs
   ON arstates.replica_id = dbcs.replica_id
LEFT OUTER JOIN master.sys.dm_hadr_database_replica_states AS dbrs
   ON dbcs.replica_id = dbrs.replica_id AND dbcs.group_database_id = dbrs.group_database_id
WHERE ISNULL(arstates.role, 3) = 2 AND ISNULL(dbcs.is_database_joined, 0) = 1
ORDER BY  dbcs.database_name

Monitoring AGs in WSFC Cluster:

select * from sys.dm_hadr_cluster

select * from sys.dm_hadr_cluster_members

select * from sys.dm_hadr_cluster_networks

select * from sys.dm_hadr_instance_node_map

select * from sys.dm_hadr_name_id_map

Monitoring AGs:

select * from sys.availability_groups

select * from sys.availability_groups_cluster

select * from sys.dm_hadr_availability_group_states

monitoring availability replicas

select * from sys.availability_replicas

select * from sys.availability_read_only_routing_lists

select * from sys.dm_hadr_availability_replica_cluster_nodes

select * from sys.dm_hadr_availability_replica_cluster_states

select * from sys.dm_hadr_availability_replica_states

select  sys.fn_hadr_backup_is_preferred_replica ('DBNAME') -- Used to determine if the current replica is the preferred backup replica.

Monitoring Availability databases :

select * from sys.availability_databases_cluster

select * from sys.databases

select * from sys.dm_hadr_auto_page_repair

select * from sys.dm_hadr_database_replica_states

select * from sys.dm_hadr_database_replica_cluster_states

Monitor the availability group listeners:

select * from sys.availability_group_listener_ip_addresses

select * from sys.availability_group_listeners

select * from sys.dm_tcp_listener_states

Please refer the below queries for AlwaysOn Availability Groups monitoring reference:

    SERVERPROPERTY (Transact-SQL)

    sys.availability_group_listener_ip_addresses (Transact-SQL)

    sys.availability_group_listeners (Transact-SQL)

    sys.availability_databases_cluster (Transact-SQL)

    sys.availability_groups (Transact-SQL)

    sys.availability_read_only_routing_lists (Transact-SQL)

    sys.availability_replicas (Transact-SQL)

    sys.dm_hadr_availability_replica_cluster_nodes (Transact-SQL)

    sys.dm_hadr_availability_replica_cluster_states (Transact-SQL)

    sys.database_mirroring_endpoints (Transact-SQL)

    sys.dm_hadr_auto_page_repair (Transact-SQL)

    sys.dm_hadr_availability_group_states (Transact-SQL)

    sys.dm_hadr_availability_replica_cluster_states (Transact-SQL)

    sys.dm_hadr_availability_replica_states (Transact-SQL)

    sys.dm_hadr_database_replica_states (Transact-SQL)

    sys.dm_hadr_database_replica_cluster_states (Transact-SQL)

    sys.dm_hadr_cluster (Transact-SQL)

    sys.dm_hadr_cluster_members (Transact-SQL)

    sys.dm_hadr_cluster_networks (Transact-SQL)

    sys.dm_hadr_database_replica_cluster_states (Transact-SQL)

    sys.dm_hadr_database_replica_states (Transact-SQL)

    sys.dm_hadr_instance_node_map (Transact-SQL)

    sys.dm_hadr_name_id_map (Transact-SQL)

    sys.dm_os_performance_counters (Transact-SQL)

    sys.dm_tcp_listener_states (Transact-SQL)

    sys.fn_hadr_backup_is_preferred_replica (Transact-SQL)


Thanks To: RAJU RASAGOUNDER NZ