Update Statistics With Full Scan in SQL Server
We all know to keep auto statistics update ON for a SQL server databases little overkill the performance and query may or may not use correct statistics and may choose the non-optimal execution plan. This may slow down the performance of complex queries to be run faster. Also, it is not a good idea to rebuild fragmented indexes every day in a busy production environment where thousands of query already running and there is no window for database maintenance task.
When you will run index rebuild operation on a busy database you may encounter Query Timeout error for other running queries on a larger database. So the alternative and best solution are to update statistics with a full scan. Assuming you already knowing update statistics with sp_updatestats only update statistics a sample of records of the table and with full scan, it will scan the entire table.
DECLARE @tablename varchar(80),@shemaname varchar(80)
DECLARE @SQL AS NVARCHAR(200)
DECLARE TblName_cursor CURSOR FOR
SELECT t.name,s.name FROM sys.tables t join sys.schemas s
on s.schema_id=t.schema_id
OPEN TblName_cursor
FETCH NEXT FROM TblName_cursor
INTO @tablename,@shemaname
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = 'UPDATE STATISTICS '+@shemaname+'.[' + @TableName + '] WITH FULLSCAN '
EXEC sp_executesql @statement = @SQL
FETCH NEXT FROM TblName_cursor
INTO @tablename,@shemaname
END
CLOSE TblName_cursor
DEALLOCATE TblName_cursor
Instead of updating statistics for each table we can use below script to update statistics for all tables of a database