/*============================================================================
  File:     5a_Baselines_CacheUsage_Setup.sql

  Summary:  This script contains the statements to
			create the table to store Cache Usage 
			information and the queries to review 
			the data.

  Date:     April 2015

  SQL Server Version: 2005/2008/2008R2/2012/2014
------------------------------------------------------------------------------
  Written by Erin Stellato, SQLskills.com

  (c) 2015, SQLskills.com. All rights reserved.

  For more scripts and sample code, check out 
    http://www.SQLskills.com

  You may alter this code for your own *non-commercial* purposes. You may
  republish altered code as long as you include this copyright and give due
  credit, but you must obtain prior permission before blogging this code.
  
  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF 
  ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED 
  TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
  PARTICULAR PURPOSE.
============================================================================*/

USE [BaselineData]
GO

CREATE TABLE [dbo].[SQLskills_CacheUseByDB](
	[CaptureDate] [DATETIME] NOT NULL,
	[Rownum] [INT] IDENTITY(1,1),
	[DatabaseName] [nvarchar](128) NULL,
	[CachedSizeMB] [decimal](10, 2) NULL
	);
GO


CREATE CLUSTERED INDEX [CI_SQLskills_CacheUseByDB] ON [dbo].[SQLskills_CacheUseByDB] ([CaptureDate],[RowID]);

/*
	Query for scheduled job
*/

INSERT INTO [dbo].[SQLskills_CacheUseByDB] (
	[CaptureDate],
	[DatabaseName],
	[CachedSizeMB])
SELECT 
	GETDATE(),
	DB_NAME(database_id),
	CAST(COUNT(*) * 8/1024.0 AS DECIMAL (10,2)) 
FROM sys.dm_os_buffer_descriptors WITH (NOLOCK)
WHERE database_id > 4 -- system databases
AND database_id <> 32767 -- ResourceDB
GROUP BY DB_NAME(database_id)
ORDER BY 3 DESC OPTION (RECOMPILE);