获取存储过程所在的数据库名称

Get the database name in which Stored Procedure exists

我有 SQL 服务器 2008,其中有 10 个不同的数据库,现在我想搜索一个存储过程,该存储过程存在于哪个数据库中。

被一些人提到为重复......没有正确阅读我的问题。我的要求是我需要验证 'SP_Email' 程序。我这个程序存在于哪个数据库中

您需要查询 master 数据库的 sys.databases 以获得数据库列表,对于您获得的每个数据库名称,您需要查询 db_name.sys.procedures 以检查它是否存在。

尝试以下查询并提供反馈:

use master
go
declare @FullQuery varchar(max)
declare @DBName varchar(50)
set @FullQuery=''
declare cr cursor for select name from sys.databases where database_id > 4
open cr
fetch next from cr into @DBName
while(@@fetch_status=0)
begin
set @FullQuery=@FullQuery+
    ' select name  COLLATE SQL_Latin1_General_CP1_CI_AS from '+@DBName+'.sys.procedures where name like ''%proc_name%'' union'
fetch next from cr into @DBName
end
close cr
deallocate cr
set @FullQuery=substring(@FullQuery,1,len(@FullQuery)-5)
exec (@FullQuery)
SELECT OBJECT_ID('DataBase1.SchemaName.StoredProcedureName') / 
OBJECT_ID('DataBase2.SchemaName.StoredProcedureName') / 
OBJECT_ID('DataBase3.SchemaName.StoredProcedureName') /
...

如果没有这样的程序,它会return NULL。如果所有数据库都在同一个实例上,这将起作用。

你可以试试这个:

EXEC sp_msforeachdb 
'if exists(select 1 from [?].sys.objects where name=''SP_Email'')
select ''?'' as FoundInDatabase from [?].sys.objects where name=''SP_Email'''

请试试这个。

SELECT name DatabaseName
FROM sys.databases
WHERE OBJECT_ID(QUOTENAME(name) + '.dbo.ProcedureNameHere', 'P') IS NOT NULL;

这将 return 该特定对象所在的数据库名称。

ProcedureNameHere 替换为您的过程名称。在你的情况下,它将是 SP_Email 其余的保持原样。