﻿CREATE  procedure [dbo].[AMB_Cerca] (@word1 varchar(max) = 'DMECST71D10H501E') as     
BEGIN    
declare @Datab varchar(50)
declare @query varchar(max)
declare @dbid smallint = 1
declare @numdb smallint = 1
select @numdb =  max(database_id) from  master.sys.databases
IF OBJECT_ID('tempdb.dbo.#temp1', 'U') IS NOT NULL DROP TABLE #temp1;
create table #temp1 (DatabaseName Varchar(50), NomeOggetto varchar(50), TipoOggetto varchar(max))
while  (@dbid <= @numdb ) 
begin 
	SELECT  @Datab= name FROM master.sys.databases where database_id = @dbid
	if @Datab <> 'tempdb'
	begin
		set @query = 
		'Insert Into  #temp1 SELECT DISTINCT ''' + @Datab + ''' as DatabaseName,
		o.name AS Object_Name,
		o.type_desc
		FROM ' + @Datab+'.sys.sql_modules m
		INNER JOIN ' + @Datab+ '.sys.objects o
		ON m.object_id = o.object_id
		WHERE upper(m.definition) like ''%' + @word1 + '%'''
		begin try
			print @query
			exec (@query)
		end try
		begin catch
			Insert Into  #temp1 select name , 'si è verificato un errore',
			ISNULL( error_message(),'') 
			FROM master.sys.databases where database_id = @dbid
		end catch 
    end
	set @dbid = @dbid + 1
end
select * from #temp1 order by 1, 3, 2
drop table #temp1
END