Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing SQL query on multiple databases

I know my post has a very similar title to other ones in this forum, but I really couldn't find the answer I need.

Here is my problem, I have a SQL Server running on my Windows Server. Inside my SQL Server, I have around 30 databases. All of them have the same tables, and the same stored procedures.

Now, here is the problem, I have this huge script that I need to run in all of these databases. I wish I could do it just once against all my databases.

I tried a couple things like go to "view" >> registered servers >> local server groups >> new server registration. But this solution is for many servers, not many databases.

I know I could do it by typing the database name, but the query is really huge, so it would take too long to run in all databases.

Does anybody have any idea if that is possible?

like image 351
Arturio Avatar asked Sep 05 '16 18:09

Arturio


People also ask

Can you run SQL query across multiple databases?

Elastic database query (preview) for Azure SQL Database allows you to run T-SQL queries that span multiple databases using a single connection point.

How run SQL query on all databases?

There is a handy undocumented stored procedure that allows you to do this without needing to set up a cursor against your sysdatabases table in the master database. This can be done by using sp_MSforeachdb to run the same command in all databases.

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

You can use WHILE loop over all database names and inside loop execute query with EXECUTE. I think that statement SET @dbname = ... could be better, but this works too.

DECLARE @rn INT = 1, @dbname varchar(MAX) = '';
WHILE @dbname IS NOT NULL 
BEGIN
    SET @dbname = (SELECT name FROM (SELECT name, ROW_NUMBER() OVER (ORDER BY name) rn 
        FROM sys.databases WHERE name NOT IN('master','tempdb')) t WHERE rn = @rn);

    IF @dbname <> '' AND @dbname IS NOT NULL
        EXECUTE ('use ['+@dbname+'];

            /* Your script code here */
            UPDATE some_table SET ... ;

        ');
    SET @rn = @rn + 1;
END;
like image 120
marioosh Avatar answered Sep 19 '22 15:09

marioosh