Generate DBCC SHOWCONTIG Commands for All User Tables in SQL Server

Generate DBCC SHOWCONTIG Commands for All User Tables in SQL Server

Database administrators frequently need to monitor table and index fragmentation to maintain optimal database performance. This SQL Server script provides an efficient way to generate DBCC SHOWCONTIG commands for all user tables in your database automatically.

Purpose

The primary purpose of this script is to dynamically generate DBCC SHOWCONTIG commands for every user table in a SQL Server database. This eliminates the need to manually write individual commands for each table, saving time and ensuring comprehensive fragmentation analysis across all tables.

The SQL Script

1select 'DBCC SHOWCONTIG (' + CONVERT(varchar(12), id) + ')' + 'go' 
2from sysobjects 
3where type = 'U' 
4order by name

Code Breakdown

SELECT Statement Components

String Concatenation: The SELECT statement builds a complete DBCC command by concatenating:

  • The literal string 'DBCC SHOWCONTIG ('
  • The converted table ID using CONVERT(varchar(12), id)
  • The closing parenthesis and GO statement ')' + 'go'

CONVERT Function: The CONVERT(varchar(12), id) function transforms the numeric table ID from the sysobjects table into a varchar string with a maximum length of 12 characters.

FROM Clause

sysobjects Table: This system table contains metadata about all database objects including tables, views, stored procedures, and other database objects. Each row represents one database object with its corresponding object ID and type.

WHERE Clause

Type Filter: The condition type = 'U' specifically filters for user tables only, excluding system tables, views, stored procedures, and other object types. The 'U' designation stands for "User Table" in SQL Server's object type classification.

ORDER BY Clause

Alphabetical Sorting: Results are ordered by the name column, ensuring the generated commands are listed alphabetically by table name for better organization and readability.

Key Points

Automated Command Generation

This script automates the tedious process of writing individual DBCC SHOWCONTIG commands for each table, particularly valuable in databases with numerous tables.

Comprehensive Coverage

By querying sysobjects with the user table filter, the script ensures no user tables are missed during fragmentation analysis.

Ready-to-Execute Output

The generated output includes the 'GO' batch separator, making the results immediately executable in SQL Server Management Studio or other query tools.

Legacy Compatibility

This script uses the older sysobjects system view, which works across multiple SQL Server versions but may be considered legacy in newer versions.

Insights and Best Practices

When to Use This Script

Regular Maintenance: Incorporate this into regular database maintenance routines to monitor fragmentation levels across all tables.

Performance Troubleshooting: Use when investigating performance issues that might be related to table or index fragmentation.

Post-Maintenance Verification: Execute after major data operations to verify fragmentation levels.

Modernization Considerations

For SQL Server 2005 and later versions, consider using the more modern system views:

1SELECT 'DBCC SHOWCONTIG (' + CONVERT(varchar(12), object_id) + ') WITH TABLERESULTS' + CHAR(13) + 'GO'
2FROM sys.tables
3ORDER BY name

Enhanced Output Options

Consider adding the WITH TABLERESULTS option to get structured, parseable output:

  • Provides results in a tabular format
  • Easier to analyze programmatically
  • Better for automated reporting

Performance Considerations

Resource Usage: DBCC SHOWCONTIG can be resource-intensive on large tables. Consider running during maintenance windows.

Blocking: The command may cause brief blocking on active tables, so timing is important in production environments.

Alternative Approaches

Using Dynamic SQL

For more advanced scenarios, you might wrap this in dynamic SQL to automatically execute the generated commands:

1DECLARE @sql NVARCHAR(MAX) = ''
2SELECT @sql = @sql + 'DBCC SHOWCONTIG (' + CONVERT(varchar(12), id) + ') WITH TABLERESULTS' + CHAR(13) + 'GO' + CHAR(13)
3FROM sysobjects 
4WHERE type = 'U' 
5ORDER BY name
6
7EXEC sp_executesql @sql

Modern Fragmentation Analysis

For comprehensive fragmentation analysis in newer SQL Server versions, consider using sys.dm_db_index_physical_stats which provides more detailed information without the overhead of DBCC commands.

Conclusion

This simple yet effective script demonstrates the power of dynamic command generation in SQL Server database administration. While the approach uses legacy system views, it remains functional across SQL Server versions and provides a quick way to generate fragmentation analysis commands for all user tables. Database administrators should consider modernizing this approach using current system views and dynamic management views for enhanced functionality and better performance in contemporary SQL Server environments.

References

Posts in this series