Archive for April, 2014

Identify potential free space in Database files before shrinking – TSQL Query

April 27, 2014 3 comments

Today someone in office asked me:

"How can I know how much free space might be left in a Database to Shrink 
before actually Shrinking it?"


–> I told it is simple, go to SSMS, select Database -> Right click -> select Task -> select Shrink -> select either Database/File.


–> It will show you Available Free Space, of the whole Database or each mdf/ldf/ndf file(s).


–> He said he already knows it, his real ask was:

"what if you've hundreds of Databases and want to know the stats for each 
of them? Is there any SQL Query which can give you this stats, so that you can 
run it against each or all Database?"


I opened SQL Profiler, ran it against the instance and again performed all manual steps defined above to check the Free space. After the Shrink File pop-up window appeared I went back to the Profiler and stopped it, which threw me lot of typical SQL Queries generated by SQL Server DB engine. I searched and found the desired query that I was looking for. I slightly tweaked the query according to my needs and here it is:

USE [AdventureWorks2012]

	db_name()			AS [DatabaseName],				AS [DB_File_Name],
	s.physical_name		AS [FileName],
	s.size * CONVERT(float,8) AS [TotalSize],
	CAST(CASE s.type WHEN 2 
			THEN s.size * CONVERT(float,8) 
			ELSE dfs.allocated_extent_page_count*convert(float,8) 
		END AS float)	AS [UsedSpace],
	CASE s.type WHEN 2 
		THEN 0 
		ELSE s.size * CONVERT(float,8) - dfs.allocated_extent_page_count*convert(float,8) 
	END					AS [AvailableFreeSpace] 
from sys.database_files AS s 
left outer join sys.dm_db_file_space_usage as dfs 
	ON dfs.database_id = db_id() 
	AND dfs.file_id = s.file_id
where (s.drop_lsn IS NULL)

–> Output:


To Shrink Database Files check my earlier blog post:


Query to check AlwaysON Replica Latency for the LSNs (Log Sequence Numbers) by using DMVs

April 11, 2014 Leave a comment

	 ag.NAME AS 'AG Name'
	,ar.replica_server_name AS 'AG Replica Server'
	,DB_NAME(drs.database_id) AS 'Database Name'
		WHEN ars.is_local = 1
	END AS 'Is AG Replica Local'
		WHEN ars.role_desc IS NULL
		ELSE ars.role_desc
	END AS 'AG Replica Role'
	,ar.availability_mode_desc AS 'Sync Mode'
	,drs.synchronization_state_desc AS SyncState
	,agl.dns_name AS 'Listener Name'
	,datediff(s, last_hardened_time, getdate()) / 60 AS 'Seconds Behind Primary'

FROM sys.availability_groups AS ag 

INNER JOIN sys.availability_replicas AS ar 
ON ag.group_id = ar.group_id

INNER JOIN sys.dm_hadr_availability_replica_states AS ars 
ON ar.replica_id = ars.replica_id

INNER JOIN sys.dm_hadr_database_replica_states drs 
ON ag.group_id = drs.group_id
AND drs.replica_id = ars.replica_id

INNER JOIN sys.availability_group_listeners AS agl
ON agl.group_id = ars.group_id

ORDER BY datediff(s, last_hardened_time, getdate()) DESC;