Why you need these scripts
Two short T-SQL scripts can save you hours of digging through an unfamiliar SQL Server database: one finds where a value lives, the other finds where a column lives.
If you support an ERP system such as Microsoft Dynamics GP, you know the feeling. A user says “the word Allowance shows up on a screen somewhere” or “where else is the salesperson ID stored?”, and you are staring at a database with thousands of tables and cryptic names like RM00101 or SOP30200.
You could click through tables one by one in SQL Server Management Studio. Or you could let the system catalog do the work. This article walks through both scripts, explains how each line works, and covers the caveats you should know before running them in production.
Script 1: Search every text column for a word or pattern
This script scans every character column in a set of tables and reports which table and column contain your search text, plus how many rows match. You control the scope with a table-name filter: N'%' searches every table, while N'EXT%' limits the search to tables whose names start with EXT (in Dynamics GP, the Extender tables).
DECLARE @SearchValue nvarchar(200) = N'%Allowance%'; -- the text you're looking for
DECLARE @TableFilter sysname = N'EXT%'; -- N'%' to search every table
DECLARE @Pattern nvarchar(210) = N'%' + @SearchValue + N'%';
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results;
CREATE TABLE #Results (TableName nvarchar(300), ColumnName sysname, MatchCount int);
DECLARE @sql nvarchar(max) = N'';
SELECT @sql +=
N'INSERT INTO #Results SELECT N' + QUOTENAME(s.name + N'.' + t.name, '''')
+ N', N' + QUOTENAME(c.name, '''')
+ N', COUNT(*) FROM ' + QUOTENAME(s.name) + N'.' + QUOTENAME(t.name)
+ N' WITH (NOLOCK) WHERE ' + QUOTENAME(c.name) + N' LIKE @p HAVING COUNT(*) > 0;'
+ CHAR(13) + CHAR(10)
FROM sys.tables t
JOIN sys.schemas s ON s.schema_id = t.schema_id
JOIN sys.columns c ON c.object_id = t.object_id
JOIN sys.types ty ON ty.user_type_id = c.user_type_id
WHERE ty.name IN ('char', 'varchar', 'nchar', 'nvarchar')
AND t.name LIKE @TableFilter
AND (c.max_length = -1 OR c.max_length >= LEN(@SearchValue));
EXEC sp_executesql @sql, N'@p nvarchar(210)', @p = @Pattern;
SELECT * FROM #Results ORDER BY TableName, ColumnName;
How it works
- Set your inputs.
@SearchValueis the text to find and@TableFilteris aLIKEpattern for table names. The script wraps the search value in%wildcards so it matches anywhere inside a column. - Prepare a results table. A temp table,
#Results, collects one row per table and column that has at least one match. The script drops any leftover copy first, so you can rerun it in the same session. - Build one query per column. The
SELECT @sql +=statement reads the system catalog (sys.tables,sys.schemas,sys.columns,sys.types) and appends anINSERT … SELECT COUNT(*)statement to@sqlfor every qualifying column. Onlychar,varchar,ncharandnvarcharcolumns are included, and columns too short to hold the search text are skipped. - Quote names safely.
QUOTENAMEwraps schema, table and column names in brackets, so names with spaces or reserved words don’t break the generated SQL. Used with'''', it also turns names into safe string literals for the result rows. - Run everything in one go.
sp_executesqlexecutes the generated batch and passes the search pattern as the parameter@p, rather than pasting it into the SQL text. That keeps quotes in your search value from causing errors or SQL injection. - Keep only hits.
HAVING COUNT(*) > 0means columns with no matches never reach#Results, so the finalSELECTshows only the places worth looking at.
The output is a short list such as dbo.EXT00100 | Field_Name | 12: the table, the column, and the number of matching rows. From there you can write a targeted query against that one table.
Script 1: Tips and caveats
The script is safe to run because it only reads data, but it can be heavy, so narrow the scope whenever you can.
- It can be slow. A
LIKE '%text%'search cannot use an index, so every qualifying column means a full scan of its table. On a large company database withN'%'as the filter, expect minutes rather than seconds. Run it off-hours or against a test copy first. NOLOCKtrades accuracy for politeness.WITH (NOLOCK)stops the search from blocking users, but it can read uncommitted or in-flight rows. That is fine for “where is this text?” and not fine for anything you report as a count of record.- You don’t need wildcards in
@SearchValue. The script already adds%on both sides. TypingN'Allowance'gives the same result asN'%Allowance%'and makes the length check (LEN(@SearchValue)) more accurate, since the%signs count toward it. - The length check is approximate.
max_lengthis stored in bytes, so annvarchar(10)column reports 20. Some shortnvarcharcolumns may be searched when they can’t possibly match, which only costs a little time. - Some data is out of scope. Legacy
textandntextcolumns, views, and numeric or date columns are not searched. Add'text'and'ntext'to the type list if your database still uses them. - Case sensitivity follows your collation. On most SQL Server installs (case-insensitive collations),
allowanceandAllowancematch the same rows.
Script 2: Find every table and view that contains a column
This script answers a different question: not “where is this value?” but “where is this field?”. Give it a column name and it lists every table and view that has it, along with the data type and length.
SELECT
c.TABLE_SCHEMA,
c.TABLE_NAME,
c.COLUMN_NAME,
c.DATA_TYPE,
c.CHARACTER_MAXIMUM_LENGTH,
t.TABLE_TYPE
FROM INFORMATION_SCHEMA.COLUMNS c
JOIN INFORMATION_SCHEMA.TABLES t
ON c.TABLE_SCHEMA = t.TABLE_SCHEMA
AND c.TABLE_NAME = t.TABLE_NAME
WHERE c.COLUMN_NAME = '<field you want to search e.g. SLPRSNID'>
ORDER BY c.TABLE_NAME;
How it works
INFORMATION_SCHEMA.COLUMNS holds one row for every column in every table and view in the current database. Joining it to INFORMATION_SCHEMA.TABLES adds TABLE_TYPE, which tells you whether each hit is a BASE TABLE or a VIEW.
The example searches for SLPRSNID, the salesperson ID field in Dynamics GP. The result shows every place that field appears:
| Column | What it tells you |
|---|---|
TABLE_SCHEMA | The schema, usually dbo |
TABLE_NAME | The table or view that holds the column |
COLUMN_NAME | The column you searched for |
DATA_TYPE | The type, such as char or int |
CHARACTER_MAXIMUM_LENGTH | Maximum length for text columns; empty for numbers and dates |
TABLE_TYPE | BASE TABLE or VIEW |
Because this query reads only metadata, it returns almost instantly, even on a database with thousands of tables.
Useful variations
- Partial names: change the filter to
WHERE c.COLUMN_NAME LIKE '%SLPRSN%'to catch related fields. - Tables only: add
AND t.TABLE_TYPE = 'BASE TABLE'to skip views. - Spot type mismatches: sort by
DATA_TYPE, CHARACTER_MAXIMUM_LENGTHto see whether the same field is defined differently in different tables, which often causes join or truncation problems.
Using both scripts together
The two scripts work best as a pair: Script 1 finds the column that holds a value, and Script 2 shows everywhere else that column appears.
- Start with the value. A user reports a label or code on screen, such as Allowance. Run Script 1 with a narrow table filter to find the table and column that store it.
- Follow the field. Take the column name Script 1 returned and run it through Script 2. You now see every table and view that shares the field, which usually reveals the related header, detail and history tables.
- Write the real query. With the tables and data types in hand, you can join the right tables, size your variables correctly and avoid conversion errors.
The same approach works well before a data cleanup or a field-length change, when you need to know every place a value or column could be affected.
Conclusion
Keep both scripts in your snippets folder: one turns “it’s in there somewhere” into a table and column name, and the other maps every place a field lives.
Script 1 does the heavy lifting by generating and running a search across every text column you point it at, so scope it with a table filter and run it outside busy hours. Script 2 is a lightweight metadata lookup you can run any time. Together they make an unfamiliar database a lot less mysterious.