Updating Statistics with Cursor in SQL Server
Hello everyone,
In this article, I will try to give information about updating Statistics with Cursor in SQL Server.
Although Statistics are updated automatically in SQL Server, sometimes they need to be updated manually.
You can easily do this using the code below.
DECLARE @sql NVARCHAR(500);
DECLARE @tableName NVARCHAR(200);
DECLARE cls CURSOR FOR
SELECT '[' + TABLE_SCHEMA + '].' + '[' + TABLE_NAME + ']'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE';
OPEN cls;
FETCH NEXT FROM cls
INTO @tableName;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = N'UPDATE STATISTICS ' + @tableName;
EXEC sp_executesql @sql;
FETCH NEXT FROM cls
INTO @tableName;
END;
CLOSE cls;
DEALLOCATE cls;
Good luck to everyone in business and life.