Friday, June 6, 2008

sp_MSForEachTable

I had to improve performance on a just-restored database, and remembered of one of my favorite undocumented SQL Server commands, sp_MSForEachTable. In the below example, the "?" is the variable for where the table name should go in the statement you want to execute:


EXEC sp_MSForEachTable "UPDATE STATISTICS ?"
Another quick example - to print out all the table names in a db, just run:


EXEC sp_MSForEachTable "PRINT '?'"
FYI, there's also sp_MSForEachDB that lets you do the same operation on all databases on the server. Learning this alone was worth the price of Brian Knight's "Admin 911: SQL Server 2000" book.

No comments: