Run A Query Against Each Database in SQL

08/23/21

Use this SQL script to loop through each database on an instance and run a query against each database.

--This query will return a listing of all tables in all databases on a SQL instance: 
DECLARE @command varchar(1000) 
SELECT @command = 'USE ? SELECT DB_Name(), name FROM sysobjects WHERE xtype = ''U'' ORDER BY name' 
EXEC sp_MSforeachdb @command 

We're available if you need assistance implementing custom SQL code. Contact us for help!

Share This: 

Related Resources

envelope