Ads

19 March 2013

DBGrowth - Query

-- This will create a table in MSDB DB.
-- WWSQLDBGrowth will be the table name


if (select count(1)from msdb..sysobjects where name = 'WWSQLDBGrowth' and xtype = 'U') = 0
-- not exists ((select * from msdb..sysobjects where id = object_id(N'[dbo].[WWSQLDBGrowth]') and OBJECTPROPERTY(id, N'IsUserTable') = 1))
begin
CREATE TABLE [MSDB]..[WWSQLDBGrowth] (
[DBName] [varchar] (255),
[FileGroup] [varchar] (255),
[FileName] [varchar] (255),
[FilePath] [varchar] (1000),
[SizeInMB] [float],
[UsedInMB] [float] ,
[FreeInMB] [float],
[AuditDate] datetime
) ON [PRIMARY]
end
DECLARE @DBName varchar(255)
DECLARE DBSize_cursor CURSOR FOR
select name from master..sysdatabases (nolock) --where status < 48
OPEN DBSize_cursor
 FETCH NEXT FROM DBSize_cursor INTO @DBName
WHILE @@FETCH_STATUS = 0
BEGIN
 exec ('use ' + @DBName + ' insert into [MSDB]..[WWSQLDBGrowth] select ''' + @DBName + ''' as DBName ,  groupname as FileGroup,  name as FileName, filename as FilePath, (size*8)/1024. as SizeInMB , (fileproperty(name, ''SpaceUsed''  )*8)/1024. as UsedInMB , ((size - fileproperty(name,''SpaceUsed''))*8)/1024. as FreeInMB, Getdate() as AuditDate FROM sysfiles a LEFT JOIN sysfilegroups b ON a.groupid = b.groupid')
   FETCH NEXT FROM DBSize_cursor INTO @DBName
END
CLOSE DBSize_cursor
DEALLOCATE DBSize_cursor
GO

No comments:

Post a Comment