views:

164

answers:

5
+1  Q: 

SQL Super Search

Does anyone have a good method for searching an entire database for a given value? I have a specific string I'm looking for, it's in TableA, and it's also a FK to some other table, TableB, except I don't know which table/column that is.

Assuming there's a jillion tables and I don't want to look through them all, and maybe will have to do this in several different cases, what would be the best way?

Since I didn't want a Code-SQL bridge, my only all-SQL idea was:

select tablename and column_name from INFORMATION_SCHEMA.COLUMNS

...then use a cursor to flip through all the columns, and for all the datatypes of nvarchar I would execute dynamic SQL like:

SELECT * from @table where @column =  @myvalue

Needless to say, this is slow AND a memory hog.

Anyone got any ideas?

+6  A: 

Dump the database and grep?

I guess a more focused question might be: if you don't know how the schema works, what are you going to do with the answer you get anyway?

Andy Ross
+1 for _if you don't know how the schema works, what are you going to do with the answer you get anyway?_
KM
well, its a FK. I just need to build a link between two tables so I can store associated data. The data itself isn't important right now, just as long as I link it so it's captured. How does one go about dumping the whole DB to text?
LoveMeSomeCode
+3  A: 

Here are a couple of links talking about how to do this:

Both of them use the approach you were hoping to avoid. Refine them so that they only searched columns that were foreign keys should improve their performance by eliminating the searching of unnecessary tables.

Ben Gribaudo
This is the way I ended up going. Also, a +1 for making me feel better about the way I was already doing it :)
LoveMeSomeCode
A: 

Just make SP that searches in all relevant columns using OR.

Why don't you know which columns to search on?

If the list of columns is ever-shifting, then you just need to make sure that whatever process results in changing the schema would result in the change in this stored procedure.

If the list of the columns is just too dang big for you to type up inot the SP, use some elementary perl/grep/whatnot to do it in 1 line, e.g for SYBASE.

my_dump_table_schema.pl|egrep "( CHAR| VARCHAR)"|awk '{$1}'|tr "\012" " "|perl -pe '{s/ / = \@SEARCH_VALUE OR /g}'; echo ' = @SEARCH_VALUE'

The last echo is needed to add the value to last column

Lemurik
A: 

to dump your data, read up on the bcp Utility

KM
+2  A: 

Here's a solution I wrote several years ago: http://www.users.drew.edu/skass/sql/SearchAllTables.sql.txt

Steve Kass
that's actually what I had more or less. It's really slow on this huge db, and a memory hog, but it does the job.
LoveMeSomeCode