Author:
@kisinamso
Purpose: Automatically update table statistics and log the process.
Updates statistics on all tables within the specified database or all user databases.
Each update is logged into the StatisticsUpdateLog table.
| Parameter Name | Type | Description |
|---|---|---|
@DatabaseName |
SYSNAME |
If NULL, runs for all user databases. If a specific name is given, runs only for that one. |
Automatically created if it doesn't exist.
| Column Name | Data Type | Description |
|---|---|---|
LogID |
INT (IDENTITY) |
Auto-increment identity column |
DatabaseName |
SYSNAME |
Database where update was run |
SchemaName |
SYSNAME |
Schema of the table |
TableName |
SYSNAME |
Name of the table |
StatisticName |
SYSNAME |
Name of the updated statistic |
UpdateDate |
DATETIME |
Timestamp of the update |
Status |
VARCHAR(10) |
'Success' or 'Fail' |
ErrorMessage |
NVARCHAR(MAX) |
Error message if any |
- If
@DatabaseNameis NULL, runs on all user databases. - For each database:
- Retrieves all tables and their statistics from
sys.stats. - Generates
UPDATE STATISTICS ... WITH FULLSCANcommands.
- Retrieves all tables and their statistics from
- Executes each update inside a
TRY/CATCHblock. - Logs successful updates as
"Success", and failed ones as"Fail".
- Cursor 1:
db_cursorβ Iterates through user databases. - Cursor 2:
table_cursorβ Iterates through table statistics in each database. - Dynamic SQL: Uses
sp_executesqlto execute theUPDATE STATISTICScommand.
- Requires elevated privileges; should only be run by authorized users.
WITH FULLSCANprovides more accurate stats but may be time-consuming.
- Can be scheduled using SQL Server Agent Job for periodic execution.
- The
StatisticsUpdateLogtable can be visualized via Power BI, SSRS, or other tools. - Logged entries enable historical review and auditability.
I know you wonder about this stored procedure :) Do not worry you can access with free. Click here for access.