Executing SQL query on multiple databases
ApexSQL Propagate is the tool which can help in this situation. It is used for executing single or multiple scripts on multiple databases, even multiple servers. What you should do is simply select that script, then select all databases against which you want to execute that script:
When you load scripts and databases you should just click the “Execute” button and wait for the results:
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;