Search

Friday, June 24, 2011

Update stats for all Databases at one go

declare @ServerName varchar(50), --variable to hold the ServerName
    @DatabaseName varchar(100), --variable to hold the database name
    @Command varchar(1000) --variable to hold the sql Command


-- set variables
select @ServerName=@@ServerName


-- declare the cursor
declare Cursor1 cursor for
select name from master.dbo.sysdatabases
    where  (status & 32 <> 32 and status & 128 <> 128 and status & 512 <> 512 and status & 1024 <> 1024 and status & 4096 <> 4096 and status & 2048 <> 2048)  and (name not in ('Northwind', 'Pubs'))


-- open the cursor
open Cursor1


-- fetch the first record into the cursor
fetch Cursor1 into @DatabaseName


-- while the fetch was successful
while @@fetch_status=0
begin
    -- print the header for each database
    print ''
    print '***************************'
    print 'DBCC UPDATEUSAGE Report For '+@DatabaseName
    print '***************************'
    print ''


    -- set the Command to execute
    set @Command='dbcc updateusage('+@DatabaseName+')'


    -- execute the Command
    exec(@Command)


    -- fetch the next record into the cursor
    fetch Cursor1 into @DatabaseName
end


-- close the cursor
close Cursor1


-- deallocate the cursor
deallocate Cursor1


-- tell user when the script was last run
select 'This script was executed on ' + cast(getdate() as varchar(50))

No comments:

Post a Comment