"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Wednesday, June 23, 2010

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 /* Database Name*/
GO

CREATE TABLE myTable99 (TABLE_NAME sysname, COLUMN_NAME sysname, Occurs int)
GO

SET NOCOUNT ON

DECLARE @SQL varchar(8000), @TABLE_NAME sysname, @COLUMN_NAME sysname, @Sargable varchar(80), @Count int

SELECT @Sargable =/* word to be searched*/

DECLARE insaneCursor CURSOR FOR
SELECT c.TABLE_NAME, c.COLUMN_NAME
 FROM INFORMATION_SCHEMA.Columns c INNER JOIN INFORMATION_SCHEMA.Tables t
   ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
WHERE c.DATA_TYPE IN ('char','nchar','varchar','nvarchar','text','ntext')
  AND t.TABLE_TYPE = 'BASE TABLE'

OPEN insaneCursor

FETCH NEXT FROM insaneCursor INTO @TABLE_NAME, @COLUMN_NAME

WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @SQL = 'INSERT INTO myTable99 (TABLE_NAME, COLUMN_NAME, Occurs) SELECT '
+ '''' +  @TABLE_NAME + '''' + ','
+ '''' + @COLUMN_NAME + '''' + ','
+ 'COUNT(*) FROM [' + @TABLE_NAME
+ '] WHERE [' + @COLUMN_NAME + '] Like '
+ ''''+ '%' + @Sargable + '%' + ''''
--SELECT @SQL
EXEC(@SQL)
IF @@ERROR <> 0
BEGIN
SELECT @SQL
SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = @TABLE_NAME
GOTO Error
END
FETCH NEXT FROM insaneCursor INTO @TABLE_NAME, @COLUMN_NAME
END

SELECT * FROM myTable99 WHERE Occurs <> 0


Error:
CLOSE insaneCursor
DEALLOCATE insaneCursor

#### to drop the Table and  NOCOUNT  off #####


GO

DROP TABLE myTable99
GO

SET NOCOUNT OFF


Have a nice day... 'N happy Coding :)

 jQuery Cookbook: Solutions & Examples for jQuery Developers (Animal Guide)Learning jQuery 1.3jQuery UI 1.7: The User Interface Library for jQuery

No comments: