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.

65 Views

Yavuz Selim Kart

I try to explain what I know in software and database. I am still improving myself by doing research on many programming languages. Apart from these, I am also interested in Graphic Design and Wordpress. I also have knowledge about SEO and Social media management. In short, I am a determined person who likes to work hard.

You may also like...

Don`t copy text!