Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run the same query on all the databases on an instance?

I have (for testing purposes) many dbs with the same schema (=same tables and columns basically) on a sql server 2008 r2 instance.

i would like a query like

SELECT COUNT(*) FROM CUSTOMERS 

on all DBs on the instance. I would like to have as result 2 columns:

1 - the DB Name

2 - the value of COUNT(*)

Example:

DBName  //   COUNT (*)  TestDB1 // 4  MyDB  // 5  etc... 

Note: i assume that CUSTOMERS table exists in all dbs (except master).

like image 779
LaBracca Avatar asked Aug 27 '13 10:08

LaBracca


People also ask

How do I run the same query on multiple databases in SQL Server?

Open a new Query Window and write a query which has to be executed against multiple database of a server. Right click in the window and Select an option “Run On Multiple Targets” as shown below. This will open a new window which will have all the database available on the current server listed as shown below.

Are SQL queries same for all databases?

SQL is the basic language used for all the databases. There are minor syntax changes amongst different databases, but the basic SQL syntax remains largely the same.

How do I run a SQL script on multiple databases?

To run a single script against multiple databases, you'll need to create a list of databases. Then iterate through each one and fire a USE command and then the command itself.


1 Answers

Try this one -

    SET NOCOUNT ON;          IF OBJECT_ID (N'tempdb.dbo.#temp') IS NOT NULL        DROP TABLE #temp          CREATE TABLE #temp     (           [COUNT] INT         , DB VARCHAR(50)     )          DECLARE @TableName NVARCHAR(50)      SELECT @TableName = '[dbo].[CUSTOMERS]'          DECLARE @SQL NVARCHAR(MAX)     SELECT @SQL = STUFF((         SELECT CHAR(13) + 'SELECT ' + QUOTENAME(name, '''') + ', COUNT(1) FROM ' + QUOTENAME(name) + '.' + QUOTENAME(@TableName)         FROM sys.databases          WHERE OBJECT_ID(QUOTENAME(name) + '.' + QUOTENAME(@TableName)) IS NOT NULL         FOR XML PATH(''), TYPE).value('text()[1]', 'NVARCHAR(MAX)'), 1, 1, '')          INSERT INTO #temp (DB, [COUNT])                   EXEC sys.sp_executesql @SQL          SELECT *      FROM #temp t 

Output (for example, in AdventureWorks) -

COUNT       DB ----------- -------------------------------------------------- 19972       AdventureWorks2008R2 19975       AdventureWorks2012 19472       AdventureWorks2008R2_Live 
like image 161
Devart Avatar answered Nov 11 '22 07:11

Devart