﻿CREATE  procedure [dbo].[AMB_Cerca] (@word1 varchar(max) = 'DMECST71D10H501E') as     
BEGIN    
declare @Datab varchar(300)
declare @query varchar(max)
declare @dbid smallint = 5
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(300), SchemaName Varchar(300), NomeOggetto varchar(300), TipoOggetto varchar(300), create_date datetime, modify_date datetime)
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, SCHEMA_NAME(schema_id) SchemaName, 
		o.name AS Object_Name,
		o.type_desc, create_date, modify_date
		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 'sp_helptext ''' + SchemaName + '.' + NomeOggetto + '''' sp_helptext, * from #temp1 
order by NomeOggetto, TipoOggetto, DatabaseName, SchemaName		
drop table #temp1
END