Link to home
Start Free TrialLog in
Avatar of edrz01
edrz01Flag for United States of America

asked on

Query List of Databases and then loop through to get information

I need to get the 'name' from running the 'exec sp_helpdb' and then use it in a loop whcih would run the following command against it.

use Database1 << This is the 'name' from the sp_helpdb
select name , filename , convert(decimal(12,2),round(a.size/128.000,2)) as FileSizeMB , convert(decimal(12,2),round(fileproperty(a.name,'SpaceUsed')/128.000,2)) as SpaceUsedMB , convert(decimal(12,2),round((a.size-fileproperty(a.name,'SpaceUsed'))/128.000,2)) as FreeSpaceMB from dbo.sysfiles a
go
use Database2 << This is the 'name' from the sp_helpdb
select name , filename , convert(decimal(12,2),round(a.size/128.000,2)) as FileSizeMB , convert(decimal(12,2),round(fileproperty(a.name,'SpaceUsed')/128.000,2)) as SpaceUsedMB , convert(decimal(12,2),round((a.size-fileproperty(a.name,'SpaceUsed'))/128.000,2)) as FreeSpaceMB from dbo.sysfiles a
go
use Database3 << This is the 'name' from the sp_helpdb
select name , filename , convert(decimal(12,2),round(a.size/128.000,2)) as FileSizeMB , convert(decimal(12,2),round(fileproperty(a.name,'SpaceUsed')/128.000,2)) as SpaceUsedMB , convert(decimal(12,2),round((a.size-fileproperty(a.name,'SpaceUsed'))/128.000,2)) as FreeSpaceMB from dbo.sysfiles a
go
....
ASKER CERTIFIED SOLUTION
Avatar of sachinpatil10d
sachinpatil10d
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
you can even use  sys.databases  table to get all database names

declare @dbName nvarchar(100)
declare @strSql nvarchar(1000)
declare  cur cursor for
select name from sys.databases 
open cur
fetch next from cur into @dbName
while @@FETCH_STATUS = 0
begin
	set @strSql = 'select name , filename , convert(decimal(12,2),round(a.size/128.000,2)) as FileSizeMB , 
				convert(decimal(12,2),round(fileproperty(a.name,''SpaceUsed'')/128.000,2)) as SpaceUsedMB , 
				convert(decimal(12,2),round((a.size-fileproperty(a.name,''SpaceUsed''))/128.000,2)) as FreeSpaceMB 
				from ' + @dbName + '.dbo.sysfiles a'
				print @strSql
	exec sp_executesql @strSql
	fetch next from cur into @dbName
end
close cur
deallocate cur

Open in new window

Avatar of edrz01

ASKER

Thanks! The first solution work great. I tested the second one as well but feel that the first one is best suited.