SQL Server查找存储过程

时间:2015-03-03 16:23:35

标签: sql sql-server stored-procedures

我使用的是SQL Server Management Studio,我有多个服务器连接,我需要知道每个包含多个数据库的服务器中存在特定存储过程的位置!

寻找在每台服务器上运行的查询

3 个答案:

答案 0 :(得分:0)

这是一个可以在每台服务器上运行的小脚本 我知道它使用while循环,这通常不是首选,有人可能会对其进行改进。

master数据库运行脚本。

SQL查询:

set nocount on

declare @procname varchar(150) = '<SPROCNAME_TO_FIND>'  -- SET THIS TO THE STORED PROCEDURE NAME YOU ARE LOOKING FOR

declare @alldbonserver table
      ( databasename varchar(150),
        doneflag     bit )

declare @foundtbl table
      ( countcol int,
        dbname   varchar(150) )

declare @errortbl table
      ( dbname varchar(150) )

insert @alldbonserver
     ( databasename,
       doneflag )
select sdb.name,
       0
  from sys.databases sdb

declare @curdbname varchar(150),
        @sqlcmd    varchar(max)

while exists (select 1
                from @alldbonserver
              where doneflag = 0)
begin
  select top 1
         @curdbname = databasename
    from @alldbonserver
   where doneflag = 0

   select @sqlcmd = 'select distinct 1, ''' + @curdbname + ''' as dbname from ' + @curdbname + '.sys.objects where type = ''P'' and name = ''' + @procname + ''''

   begin try
     insert @foundtbl
          ( countcol, dbname )
     exec(@sqlcmd)
   end try
   begin catch
     insert @errortbl
     values ( @curdbname )
   end catch

   update @alldbonserver
      set doneflag = 1
    where databasename = @curdbname
end

select dbname as 'Databases with stored procedure'
  from @foundtbl

select dbname as 'Unable to access databases'
  from @errortbl

set nocount off

示例输出:

Databases with stored procedure
-----------------------------------------
MainDatabase
SomeOtherDatabase

Unable to access databases
-----------------------------------------
model
ReportServer$SQLTemp
VeryPrivateDatabase

答案 1 :(得分:0)

我只是把它放在SQL2012上。它应该返回服务器上给定名称的所有存储过程。如果你将@SPName留空,你将获得所有这些。

Query使用sys.all_objects,因此您可以轻松地将其更改为对表,函数,任何或所有数据库对象的工作方式相同。

DECLARE @SPName VARCHAR(256)
SET @SPName = 'My_SP_Name'

DECLARE @DBName VARCHAR(256)
DECLARE @varSQL VARCHAR(512)
DECLARE @getDBName CURSOR
 SET @getDBName = CURSOR FOR

SELECT name
FROM sys.databases

CREATE TABLE #TmpTable (DBName VARCHAR(256),
    SchemaName VARCHAR(256),
    SPName VARCHAR(256))

OPEN @getDBName
FETCH NEXT
    FROM @getDBName INTO @DBName

WHILE @@FETCH_STATUS = 0
BEGIN
 SET @varSQL = 'USE [' + @DBName + '];
 INSERT INTO #TmpTable
 SELECT '''+ @DBName + ''' AS DBName,
 SCHEMA_NAME(schema_id) AS SchemaName,
 name AS SPName
 FROM sys.all_objects
 WHERE [type] = ''P'' AND name LIKE ''%' + @SPName + '%'''
 EXEC (@varSQL)

FETCH NEXT
    FROM @getDBName INTO @DBName
END

CLOSE @getDBName
DEALLOCATE @getDBName

SELECT *
FROM #TmpTable
DROP TABLE #TmpTable

答案 2 :(得分:0)

如果您使用的是SSMS,则可以创建一个服务器注册组,其中包含您连接的所有服务器,右键单击该组并针对该组运行此查询:exec sp_MSforeachdb 'select * from [?].sys.procedures where name=''<your_name_here>'''

此查询将枚举组中每个服务器上的每个数据库(注意:单引号就是这样的原因......)