Use a Cursor to Reindex your tables | | If you've done any heavy lifting in database programming, you have no doubt had to use a Cursor somewhere. As a database administrator, I don't really like them, but I think they are lifesavers in the right circumstances. Sometimes, there's just no way around them. This little script creates a cursor, iterates through it calling DBCC Reindex with variable names , deallocates the cursor and then updates the system statistics. It also takes advantage of Information_Schema, which if you aren't familiar with it, check out BOL and learn a little more about - it's another life saver.
CREATE PROCEDURE RedoStatsAndIndexes
AS
DECLARE @MyTable varchar(255)
DECLARE myCursor CURSOR FOR
SELECT table_name FROM information_schema.tables
WHERE table_type = 'base table'
OPEN myCursor
FETCH NEXT FROM myCursor INTO @MyTable
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Reindexing Table: ' + @MyTable
DBCC DBREINDEX(@MyTable, '', 90)
FETCH NEXT FROM myCursor INTO @MyTable
END
CLOSE myCursor
DEALLOCATE myCursor
EXEC sp_updatestats |
Enjoy! |