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

时间:2015-03-23 09:47:04

标签: sql-server database sql-server-2008 tsql stored-procedures

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

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

4 个答案:

答案 0 :(得分:13)

你可以试试这个:

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

答案 1 :(得分:1)

您需要查询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)

答案 2 :(得分:1)

请尝试这个。

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

这将返回此特定对象所在的数据库名称。

用您的过程名称替换 ProcedureNameHere 。对于您来说,这是 SP_Email ,请保持其余所有状态。

答案 3 :(得分:0)

SELECT OBJECT_ID('DataBase1.SchemaName.StoredProcedureName') / 
OBJECT_ID('DataBase2.SchemaName.StoredProcedureName') / 
OBJECT_ID('DataBase3.SchemaName.StoredProcedureName') /
...

如果没有这样的程序,它将返回NULL。如果所有数据库都在同一个实例上,这将有效。

相关问题