Press "Enter" to skip to content

Running Queries across SQL Server Databases

Ed Pollack has a query to run in many places:

A challenge that reappears periodically in the world of databases (especially database management) is the need to run code on a subset of databases and to do so in a nuanced manner. Some maintenance or metrics collection processes can be simply run against every database on a server with no ill-effect, but others may be app-specific, or need to omit specific sets of databases.

This article dives into how to create and customize your own solution, tackling everything from filtering databases to validating schema elements to error-handling.

It does surprise me a bit that there’s no officially supported built-in solution for this. I’ve used sp_foreachdb a lot because it’s readily available, free, and works better than sp_msforeachdb, though there are several available options for this task.