Tuesday, December 20, 2011

Update Statistics Using T-Sql

This script will update the statistics on all databases on a SQL Server instance (except for master, model and tempdb).

Declare
    @dbname varchar(1000),
    @parentname varchar(255),
    @SQLSTR varchar (1000),
    @ctrl char (2),
    @command varchar(1000)
Set @ctrl = char (13) + char (10)

Declare DBCUR Cursor Fast_Forward Read_Only For
Select [name]
From sysdatabases Where name not in
(
    'master',
    'model',
    'tempdb'
)
Order By name
Open DBCUR
Fetch Next From DBCUR Into @dbname
While @@Fetch_Status = 0
Begin
Select @command =
'
    use ['+@dbname+']
    Exec sp_MSForEachtable ''update statistics ? with fullscan''
'
Exec (@command)
Fetch Next From DBCUR Into @dbname
End
Close DBCUR
Deallocate DBCUR

No comments:

Post a Comment