SQL Server Management Studio - find stored procedure by name over multiple databases

前端 未结 4 473
情歌与酒
情歌与酒 2021-01-26 04:14

I have recently joined a software project that has approximately 20-40 databases.

Each database has at least 200 stored procedures, some of them have many more, so it i

4条回答
  •  情歌与酒
    2021-01-26 05:11

    You can use dynamic SQL to check procedure over all of databases in SQL Server Management Studio

    USE MASTER
    GO
    BEGIN TRAN
    
    DECLARE @strt INT,@End INT,@Database NVARCHAR(50)
    
    SELECT * INTO #T FROM Sys.databases WITH(NOLOCK) WHERE database_id>4 
    ORDER BY 1
    
    SELECT ROW_NUMBER ()OVER (ORDER BY database_Id)Db_Id,* INTO #TT FROM #T
    SET @strt=1
    SELECT @End=Max(Db_ID)FROM #tt
    
    WHILE @strt<=@END
         BEGIN
             DECLARE @string NVARCHAR(MAX)
             SELECT @Database=NAME FROM #TT WHERE Db_ID=@strt
    
            Set @string='  Select '''+@Database+'''db_Name,* from '+@Database+'.sys.objects 
              WHERE Name=''XYZ_procedure'''
    
              SET @strt=@strt+1
              PRINT @string
              EXEC(@string)
         END
    
    ROLLBACK TRAN
    

提交回复
热议问题