Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the database name in which Stored Procedure exists

I am having SQL server 2008 and i am having 10 different databases in it and now i want to search one stored procedure that in which database the stored procedure is present.

Mentioned as duplicate by some ..... with out reading my question properly. My Requirement is i need to verify 'SP_Email' procedure. I which database is this procedure exists.

like image 407
Dinesh Reddy Alla Avatar asked Mar 23 '15 09:03

Dinesh Reddy Alla


People also ask

How do I see the content of a stored procedure available in some other Databases?

Using SQL Server Management StudioIn Object Explorer, connect to an instance of Database Engine and then expand that instance. Expand Databases, expand the database in which the procedure belongs, and then expand Programmability. Expand Stored Procedures, right-click the procedure and then click View Dependencies.


3 Answers

Please try this.

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

This will return the database(s) name in which this particular object exist.

Replace ProcedureNameHere with your procedure name. In your case it would be SP_Email Keep rest of the things as it is.

like image 141
pedram Avatar answered Nov 12 '22 05:11

pedram


You can try this:

EXEC sp_msforeachdb 
'if exists(select 1 from [?].sys.objects where name=''SP_Email'')
select ''?'' as FoundInDatabase from [?].sys.objects where name=''SP_Email'''
like image 20
Rahul Tripathi Avatar answered Nov 12 '22 07:11

Rahul Tripathi


you need to query sys.databases of master database to get list of databases and for each database name you get you need to query the db_name.sys.procedures to check if it exists.

try below query and give a feedback:

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)
like image 1
nil Avatar answered Nov 12 '22 06:11

nil