Tuesday, 31 July 2018

findInCode - Stored Procedure to search code in all databases for a string

--search all databases
CREATE OR ALTER PROC tools.findInCode
(@searchstring VARCHAR(200))
AS
BEGIN
SET NOCOUNT ON
DECLARE @results TABLE (
     [searchTerm] VARCHAR(255)
    ,[databaseName] VARCHAR(255)
    ,[schemaName] VARCHAR(255)
    ,[objectName] VARCHAR(255)
 ,[typeDesc] VARCHAR(255) )
DECLARE @dbname sysname;
DECLARE @dsql nvarchar(max) = '
 SELECT ''' +@searchstring + '''  AS [search_term]
   ,DB_NAME() AS [databaseName]
   ,SCHEMA_NAME(schema_id) as schemaName
   ,o.name AS ObjectName
   ,o.type_desc AS typeDesc
 FROM sys.sql_modules m (NOLOCK)
 INNER JOIN sys.objects o (NOLOCK) ON m.object_id = o.object_id
 WHERE m.definition LIKE ''%'+@searchstring+'%''
';
DECLARE @execCommand nvarchar(max);

DECLARE dbs CURSOR STATIC LOCAL FORWARD_ONLY READ_ONLY 
FOR
SELECT name FROM sys.databases (NOLOCK)
OPEN dbs;
FETCH NEXT FROM dbs INTO @dbname;
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @execCommand = 'EXEC ' + QUOTENAME(@dbname) + '.sys.sp_executesql @dsql';

    INSERT @results
    EXEC sys.sp_executesql @execCommand, N'@dsql nvarchar(max)', @dsql

    FETCH NEXT FROM dbs INTO @dbname; 
END

CLOSE dbs;
DEALLOCATE dbs;
SELECT * FROM @results
END
GO

EXEC tools.findInCode 'findme'


No comments: