Search This Blog

2009-04-13

Searching Any String From A Database

Following stored procedure work as a search engine for database,i.e it will find any string from all of the table of SQL Server & returns the column names & corresponding table names where that input string/search string can be found.

USE /*Put the database name in which you want to search */
SET NOCOUNT ON
DECLARE @SEARCH_STRING NVARCHAR (500)DECLARE @QUERY VARCHAR (5000)DECLARE @SQLSTR NVARCHAR (4000)
SELECT @SEARCH_STRING = '' /*Put the string / word needs to be searched*/
DECLARE FIND_STRING_CURSOR CURSOR FORSELECT 'Select '''+ ''+ TABLE_NAME +''+''','''+ ''+ COLUMN_NAME +''+''', count (*) from [' + TABLE_SCHEMA + '].[' + TABLE_NAME + '] where ' + COLUMN_NAME + ' like ''%'+ @SEARCH_STRING +'%''' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME in(Select TABLE_NAME FROM INFORMATION_SCHEMA.TABLES)
Create table #temp(TABLE_NAME VARCHAR (500),COLUMN_NAME VARCHAR (500),CNT INT)
Open FIND_STRING_CURSORFETCH NEXT FROM FIND_STRING_CURSORINTO @QUERYWHILE @@FETCH_STATUS = 0
BEGINSET @SQLSTR = N'Insert into #temp ' + @QUERY Print @SQLSTR /* Optional step, can be removed */EXECUTE sp_executesql @SQLSTRFETCH NEXT FROM FIND_STRING_CURSORINTO @QUERY END
SELECT * FROM #temp WHERE CNT>0 ORDER BY 1
CLOSE FIND_STRING_CURSORDEALLOCATE FIND_STRING_CURSOR
DROP TABLE #TEMP

No comments: