Run script against all Databases
Copied from StackOverflow
-- put the entire stored procedure code in a variable
-- have it start with "PROC" so we can easily either create or alter the
-- procedure based on whether it already exists or not
DECLARE @sp_code NVARCHAR(MAX) =
'
PROC [dbo].[usp_some_proc] AS
SELECT DB_NAME()
'
-- get a list of databases to install the stored procedure to
select [s].[Name]
INTO #tbl_databases
from [sys].[databases] as [s]
-- define some variables to use in the loop
DECLARE @sql NVARCHAR(MAX);
DECLARE @execute_sql NVARCHAR(MAX);
DECLARE @database_name NVARCHAR(500);
-- iterate through each database
WHILE EXISTS (SELECT * FROM #tbl_databases)
BEGIN
-- get this iteration's database
SELECT TOP 1
@database_name = [name]
FROM #tbl_databases
-- determine whether stored procedure should be created or altered
IF OBJECT_ID(QUOTENAME(@database_name) + '.[dbo].[usp_some_proc]') IS NULL
SET @sql = 'CREATE' + @sp_code;
ELSE
SET @sql = 'ALTER' + @sp_code;
-- define some dynamic sql to execute against the appropriate database
SET @execute_sql = 'EXEC ' + QUOTENAME(@database_name) + '.[dbo].[sp_executesql] @sql';
-- execute the code to create/alter the procedure
EXEC [dbo].[sp_executesql] @execute_sql, N'@sql NVARCHAR(MAX)', @sql;
-- delete this database so the loop will process the next one
DELETE FROM #tbl_databases
WHERE [name] = @database_name
END
-- clean up :)
DROP TABLE #tbl_databases