SQL Server 2008: How to query all databases sizes?

后端 未结 15 976
伪装坚强ぢ
伪装坚强ぢ 2021-01-29 18:08

I have MS SQL 2008 R2, 500 databases. What is the most efficient, easiest and \'modern\' way to query all databases sizes.

The output should have columns:

15条回答
  •  悲&欢浪女
    2021-01-29 18:54

    sometimes SECURITY issues prevent from asking for all the db's and you need to query one by one with the db prefix, for those cases i created this dynamic query

    go
    declare @Results table ([Name] nvarchar(max), [DataFileSizeMB] int, [LogFileSizeMB] int);
    
    declare @QaQuery nvarchar(max)
    declare @name nvarchar(max)
    
    declare MY_CURSOR cursor 
      local static read_only forward_only
    for 
    select name from master.dbo.sysdatabases where name not in ('master', 'tempdb', 'model', 'msdb', 'rdsadmin');
    
    open MY_CURSOR
    fetch next from MY_CURSOR into @name
    while @@FETCH_STATUS = 0
    begin 
        if(len(@name)>0)
        begin
            print @name + ' Column Exist'
            set @QaQuery = N'select 
                                '''+@name+''' as Name
                                ,sum(case when type = 0 then size else 0 end) as DataFileSizeMB
                                ,sum(case when type = 1 then size else 0 end) as LogFileSizeMB
                            from ['+@name+'].sys.database_files
                            group by replace(name, ''_log'', '''')';
    
            insert @Results exec sp_executesql @QaQuery;
        end
      fetch next from MY_CURSOR into @name
    end
    close MY_CURSOR
    deallocate MY_CURSOR
    
    select * from @Results order by DataFileSizeMB desc
    go
    

提交回复
热议问题