Hi I have been working on a script to update statistics of all tables on all my DBs. The idea is to parametrise it later on, but just as a quick fix, and not wanting to implement Ola's scripts today, follow the script below.
I have tested it on a few servers, but before I schedule it to run on a live server Sunday morning, would like to get some ideas and share it with you.
SET NOCOUNT ON
DECLARE @DBS TABLE (I INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED,
DBNAME SYSNAME NOT NULL )
DECLARE @I INT
,@Z INT
,@SQL VARCHAR(1008)
,@j INT
,@Y INT
,@MYDB SYSNAME
INSERT INTO @DBS
SELECT s.name
FROM sys.databases s
INNER JOIN SYS.master_files F ON S.DATABASE_ID = F.database_id AND F.data_space_id = 1
WHERE S.STATE = 0 -- online
AND S.database_id > 3 -- exclude master, tempdb and model -- I left msdb
AND S.is_read_only = 0 -- read/write
AND S.user_access = 0 -- multi_user
AND S.NAME NOT IN ('TableBackups',
'Troubleshooting')
ORDER BY F.SIZE DESC
SELECT @Z = @@ROWCOUNT
SELECT @I = 1
WHILE @I <= @z BEGIN
BEGIN TRY DROP TABLE #T END TRY BEGIN CATCH END CATCH
CREATE TABLE #T( I INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED, MYSQL VARCHAR(1008) NOT NULL )
SELECT @MYDB = QUOTENAME (S.DBNAME )
,@SQL = 'USE ' + QUOTENAME (S.DBNAME ) + ';' + CHAR(13) + '
' + CHAR(13) +
'INSERT INTO #T(MYSQL) SELECT ''UPDATE STATISTICS '' + QUOTENAME(NAME) FROM SYS.TABLES WHERE TYPE = ''U'' ' + CHAR(13)
FROM @DBS s
WHERE s.I = @I
PRINT CAST (@SQL AS NTEXT)
BEGIN TRY
EXEC (@SQL)
SELECT @Y = @@ROWCOUNT
END TRY
BEGIN CATCH
SELECT @Y = 0
END CATCH
SELECT @J = 1
WHILE @J <= @y BEGIN
SELECT @SQL = 'USE ' + @MYDB + ';' + CHAR(13) + MYSQL
FROM #T
WHERE I= @J
BEGIN TRY
EXEC (@SQL)
END TRY
BEGIN CATCH
END CATCH
PRINT CAST (@SQL AS NTEXT)
SELECT @J = @J + 1
END
SELECT @I = @I +1
END /*WHILE*/