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  

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

	OPEN column_cursor  

	FETCH NEXT FROM column_cursor   
	INTO @columnname  

		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  
	CLOSE column_cursor;  
	DEALLOCATE column_cursor; 
    FETCH NEXT FROM table_cursor   
    INTO @tablename  
CLOSE table_cursor;  
DEALLOCATE table_cursor; 

SELECT * FROM #TemporaryStatisticsTable

DROP TABLE #TemporaryStatisticsTable

29 thoughts on “Search for a specific value in any column”

  1. No one can refuse the value of your article, but should you add more picture for reader can easily understand about what you want to transmit. Anyways, thank for your shared. Click Here

Leave a Reply

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