Friday, 5 March 2010

Manually reindex the fields within a table

One of the strange an annoying aspects of SQL is the way it sometimes just completely messes up the indexing on the tables. It can on occasion just become confungulated for no apparent reason resulting in extremely slow query execution. To combat such things consider running the stored proc when you have quiet moments in your database, it will run through each table and update the table statistics on that table. Vola!

CREATE PROCEDURE TableReIndexer
AS
BEGIN
-- REINDEX ALL TABLES IN THE DATABASE
DECLARE @SQLExec VARCHAR(255)
DECLARE MyCursor CURSOR FOR 
SELECT 'UPDATE STATISTICS [' + b.name + '] WITH FULLSCAN' AS [Exec Proc]
FROM sysobjects b
where b.type = 'U' AND b.category=0

OPEN MyCursor
FETCH MyCursor INTO @SQLExec
WHILE (@@FETCH_STATUS = 0)
BEGIN
EXEC (@SQLExec)
FETCH MyCursor INTO @SQLExec
END
CLOSE MyCursor
DEALLOCATE MyCursor
END
GO

No comments:

Post a Comment