SQL Clone
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

Search all columns in every table for a value

By Michael Davis,

Have you ever known a value in a database but had no clue what column or table it resided in? If so, you understand how frustrating it can be to spend great amounts of time searching through masses of information for the proverbial needle in a haystack. To help identify locations holding a given value, a search script can be used to spotlight all of the areas containing the needed character string.

The below script references the SQL Server metadata view, "information_schema.columns". As this provides a listing of all columns and tables within a database, it can be used as a foundation of a search. The script uses a common table expression query to populate a temporary table full of individual queries (one for each column in the database -- so it can get large and may take a few minutes). After that a "while" loop is used to execute these statements. The final result is a data set displaying all of the tables and columns matching the information searched for.

To use this script, simply place it within a query window and change the @searchValue parameter. I find it very helpful when used with an application UI - I can enter a value into the interface and use this script to find where in the database the value was stored.

Note: A few data types, such as image, cannot be converted to varchar and thus are ignored. The varchar data type was used as the base type (all data is converted to this) as it produced the fastest standardized value for comparison.


Total article views: 4485 | Views in the last 30 days: 3
Related Articles

Searching complete database

Searching complete database


Searching Column Name in All Tables

Use this script to search for a specific column name in all tables in a current database.


Object Search for Sql Server 2005

This script will search databases, tables, columns, stored procedures for text.


Search for a Column in all databases

This Script can be used for searching a column in SQL server 2005


Search objects in Database

Use this script to search objects in a Database. Also used to check a tables column types and detail...

michael davis