Following is a example of creating a procedure in all the databases using a loop mechanism . I couldn’t use SP_MSFOREACHDB as the procedure I was creating had many single quotations that made the procedure very difficult to handle.
The result of this needs to be copied and pasted on a new window pane and executed. The procedure needs to be assigned to @SqlStr variable
DECLARE @SqlStr nvarchar(max)
set nocount on
set @SqlStr = '
CREATE PROCEDURE [dbo].[dbmaint_StatManagement_new] (
@RowMaxCount BIGINT = 1000000,
@DaysOld INT = 7,
@MinDensity FLOAT = 1,
@Sample INT = NULL,
@Delay NCHAR(8) = NULL
)
AS
BEGIN
SET NOCOUNT ON
END '
--======================================================================================================================================================
CREATE TABLE #TableName (iid int identity(1,1) , DBName varchar(100))
insert INTO #TableName SELECT NAME FROM sys.databases WHERE NAME NOT IN ('TEMPDB,MASTER,MSDB,MODEL')ORDER BY NAME
-- SP_MSFOREACHDB 'IF EXISTS (SELECT 1 FROM ?..SYSOBJECTS WHERE NAME =''dbmaint_StatManagement'' and xtype = ''p'' ) insert into #TableName SELECT ''?'''
--======================================================================================================================================================
DECLARE @COUNT INT
,@CURRENT_ID int
,@DBName Varchar(100)
,@DBID int
,@SqlStr2 nvarchar(max)
SET @CURRENT_ID = 1
SELECT @COUNT = COUNT(1) FROM #TableName
SET @DBID = 1
WHILE @DBID < @COUNT BEGIN SELECT @DBName = DBName , @DBID = iid from #TableName where iid > @DBID ORDER BY iid DESC
SET @SqlStr2 = 'USE ' + @DBName + CHAR(10) + CHAR(13) + 'GO' + CHAR(10) + CHAR(13) + @SqlStr + CHAR(10) + CHAR(13) + 'GO' + CHAR(10) + CHAR(13)
SELECT @SqlStr2
END
DROP TABLE #TableName
Comments
Post a Comment