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?
Elastic database query (preview) for Azure SQL Database allows you to run T-SQL queries that span multiple databases using a single connection point.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With