How to Run SQL Against Every Database on a Microsoft SQL Server

Use the sp_msforeachdb stored procedure. In the following example, I needed to find out if there were any objects that were referencing a specific linked server:

DECLARE @command varchar(1000) 
SELECT @command = 'USE ? SELECT OBJECT_NAME(object_id) [?] FROM sys.sql_modules WHERE definition LIKE ''%LINKEDSERVERNAME%'''
EXEC sp_msforeachdb @command

In my case above, I labeled the column to be the same as the server that’s currently being queried.