Search ALL tables query

Listen with webReader
Published 06 October 09 10:53 PM | wmmihaa

Ever needed to scan the entire database for a specific value? I ran into problem twice in one week, so I put some thought into it, and hopefully it will help someone else.

DECLARE @wordToSearchFor varchar(50)
SET @wordToSearchFor = 'BizTalk Application Users' -- The word you search for

DECLARE @query varchar(500)
DECLARE SearchAll CURSOR FOR 
SELECT 'IF(SELECT COUNT(*) FROM [' + TABLE_SCHEMA + '].[' + TABLE_NAME
+ '] WHERE ['+COLUMN_NAME+'] = '''+@wordToSearchFor+''')>0
BEGIN SELECT * FROM [' + TABLE_SCHEMA + '].[' + TABLE_NAME
+ '] WHERE ['+COLUMN_NAME+'] = '''+@wordToSearchFor+'''
PRINT ''[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']'' END'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE LIKE '%CHAR'

OPEN SearchAll
FETCH NEXT FROM SearchAll INTO @query
WHILE @@FETCH_STATUS = 0
BEGIN
    EXEC (@query)
    FETCH NEXT FROM SearchAll INTO @query
END
CLOSE SearchAll
DEALLOCATE SearchAll

Hope this helps

Comments

# jahlen said on October 9, 2009 02:48 PM:

Nice one! Can you also do it without a cursor? ;)

I will keep it in mind as a nice challenge for the SQLUG community - who can do the fastest full database scan for a string...?

# robsteel said on December 3, 2009 05:38 PM:

I'm a big fan of your blog, so not being critical. But would this be a better post if you used LINQ and abstracted away the specific data store?

# wmmihaa said on December 4, 2009 07:41 PM:

robsteel, I bet it would! Do you have one?

# BR said on December 13, 2009 09:36 PM:

I am totally new to SQL Server and have a job in my hand to search any number in all columns in the database.

Please can you assist me.

This is bit important and urgent.

Thanks.

Please mail me if you can at bonku_roy@yahoo.com,  bonku.roy@steria.co.in

# Giovanni said on September 24, 2010 11:44 AM:

Very very Good !!! Thanks !

for search " WHERE DATA_TYPE LIKE '%TEXT'  "

error ??

help my

Leave a Comment

(required) 
(required) 
(optional)
(required) 

This Blog

News

    MVP - Microsoft Most Valuable Professional BizTalk User Group Sweden BizTalk blogdoc

    Follow me on Twitter Meet me at TechEd

    Visitors

    Locations of visitors to this page

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Syndication