Question: How to Find SQL Server Memory Use by Database and Objects?
Answer: The answer of this question is very simple, we can do this by going to sys.dm_os_buffer_descriptors.
Here is the first query which I use all the time to see which particular database is using the most memory in the SQL Server.
SELECT [DatabaseName] = CASE [database_id] WHEN 32767 THEN 'Resource DB' ELSE DB_NAME([database_id]) END, COUNT_BIG(*) [Pages in Buffer], COUNT_BIG(*)/128 [Buffer Size in MB] FROM sys.dm_os_buffer_descriptors GROUP BY [database_id] ORDER BY [Pages in Buffer] DESC;
Here is the result of the script listed above, which lists all the databases cached in memory.
Now let us see another query which returns us details about how much memory each object uses in a particular database.
SELECT obj.name [Object Name], o.type_desc [Object Type], i.name [Index Name], i.type_desc [Index Type], COUNT(*) AS [Cached Pages Count], COUNT(*)/128 AS [Cached Pages In MB] FROM sys.dm_os_buffer_descriptors AS bd INNER JOIN ( SELECT object_name(object_id) AS name, object_id ,index_id ,allocation_unit_id FROM sys.allocation_units AS au INNER JOIN sys.partitions AS p ON au.container_id = p.hobt_id AND (au.type = 1 OR au.type = 3) UNION ALL SELECT object_name(object_id) AS name, object_id ,index_id, allocation_unit_id FROM sys.allocation_units AS au INNER JOIN sys.partitions AS p ON au.container_id = p.partition_id AND au.type = 2 ) AS obj ON bd.allocation_unit_id = obj.allocation_unit_id INNER JOIN sys.indexes i ON obj.[object_id] = i.[object_id] INNER JOIN sys.objects o ON obj.[object_id] = o.[object_id] WHERE database_id = DB_ID() GROUP BY obj.name, i.type_desc, o.type_desc,i.name ORDER BY [Cached Pages In MB] DESC;
The above query will list all the objects and their type along with how much space they take in the memory.
If you ever wondered which object is taking the most memory in your database, you can use the above script for additional details.
Reference: Pinal Dave (http://blog.SQLAuthority.com)