Search for a specific value in any column

If you wonder, where is that string you see on the screen, have no idea from where it came from, and debugging would take hours (in large legacy systems), than here is my solution.
There is an outcommented line, in which you can limit the searches for specific column types. Sometimes yome data types are dying in conversion, and you need to limit also the searches these ways.
Just repalce the value in the first line, to make it work.

DECLARE @searchstring nvarchar(max) = '%SearchData%';

DECLARE @tablename nvarchar(max), @columnname nvarchar(max);
DECLARE @sql nvarchar(max) 
CREATE TABLE #TemporaryStatisticsTable
(
	tablename nvarchar(max),
	columnname nvarchar(max),
	content nvarchar(max),
)

DECLARE table_cursor CURSOR FOR   
SELECT  name
FROM 	sys.tables

OPEN table_cursor  

FETCH NEXT FROM table_cursor   
INTO @tablename  

WHILE @@FETCH_STATUS = 0  
BEGIN  
    
	DECLARE column_cursor CURSOR FOR   
	SELECT c.name from sys.columns c 
	INNER JOIN sys.tables t ON t.object_id = c.object_id AND t.name = @tablename
	--WHERE c.system_type_id IN (175, 167, 35)

	OPEN column_cursor  

	FETCH NEXT FROM column_cursor   
	INTO @columnname  

	WHILE @@FETCH_STATUS = 0  
	BEGIN  
		
		SET @sql = 'INSERT  #TemporaryStatisticsTable (tablename, columnname, content)
					SELECT ''' + @tablename + ''', ''' + @columnname + ''', 
						CAST(' + @columnname + ' as nvarchar(max))
					FROM ' + @tablename + '
					WHERE CAST(' + @columnname + ' as nvarchar(max)) LIKE ''' + @searchstring + '''
					'
		exec sp_executesql @sql

	    FETCH NEXT FROM column_cursor   
		INTO @columnname  
	END   
	CLOSE column_cursor;  
	DEALLOCATE column_cursor; 
	
    FETCH NEXT FROM table_cursor   
    INTO @tablename  
END   
CLOSE table_cursor;  
DEALLOCATE table_cursor; 

SELECT * FROM #TemporaryStatisticsTable

DROP TABLE #TemporaryStatisticsTable

Leave a Reply

Your email address will not be published. Required fields are marked *