Skip to content
  • Home
  • About Me
    • Disclaimer
    • Privacy Policy
    • Terms of Use
    • Consultant’s Toolbox
  • Solutions
    • Dynamics 365
      • D365 Business Central
      • D365 Finance & Operations
    • Dynamics GP
      • GP 2018 Toolbox
    • Dexterity
    • Royalty Management System
    • Franchisee Portal
  • Contact Me

Dynamics Insight – Modern ERP Perspectives

Driving Innovation with Microsoft Dynamics 365 (GP | BC | F&SCM), Power Platform & Data-Driven Strategy
Menu
Facebook Twitter Google+ LinkedIn
  • Home
  • About Me
    • Disclaimer
    • Privacy Policy
    • Terms of Use
    • Consultant’s Toolbox
  • Solutions
    • Dynamics 365
      • D365 Business Central
      • D365 Finance & Operations
    • Dynamics GP
      • GP 2018 Toolbox
    • Dexterity
    • Royalty Management System
    • Franchisee Portal
  • Contact Me
Home  /  Dynamics GP • SQL Server  /  Two SQL Scripts Every SQL Server Admin Should Keep Handy: Finding Data and Finding Columns
PostedinDynamics GP, SQL Server Posted on October 3, 2026

Two SQL Scripts Every SQL Server Admin Should Keep Handy: Finding Data and Finding Columns

Posted By Samuel Mathew

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

  1. Set your inputs. @SearchValue is the text to find and @TableFilter is a LIKE pattern for table names. The script wraps the search value in % wildcards so it matches anywhere inside a column.
  2. 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.
  3. Build one query per column. The SELECT @sql += statement reads the system catalog (sys.tables, sys.schemas, sys.columns, sys.types) and appends an INSERT … SELECT COUNT(*) statement to @sql for every qualifying column. Only char, varchar, nchar and nvarchar columns are included, and columns too short to hold the search text are skipped.
  4. Quote names safely. QUOTENAME wraps 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.
  5. Run everything in one go. sp_executesql executes 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.
  6. Keep only hits. HAVING COUNT(*) > 0 means columns with no matches never reach #Results, so the final SELECT shows 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 with N'%' as the filter, expect minutes rather than seconds. Run it off-hours or against a test copy first.
  • NOLOCK trades 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. Typing N'Allowance' gives the same result as N'%Allowance%' and makes the length check (LEN(@SearchValue)) more accurate, since the % signs count toward it.
  • The length check is approximate. max_length is stored in bytes, so an nvarchar(10) column reports 20. Some short nvarchar columns may be searched when they can’t possibly match, which only costs a little time.
  • Some data is out of scope. Legacy text and ntext columns, 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), allowance and Allowance match 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:

ColumnWhat it tells you
TABLE_SCHEMAThe schema, usually dbo
TABLE_NAMEThe table or view that holds the column
COLUMN_NAMEThe column you searched for
DATA_TYPEThe type, such as char or int
CHARACTER_MAXIMUM_LENGTHMaximum length for text columns; empty for numbers and dates
TABLE_TYPEBASE 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_LENGTH to 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.

  1. 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.
  2. 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.
  3. 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.

Share on Facebook Share on Twitter Share on Google+ Share on LinkedIn Share on Pinterest
Previous Article
Why Technology Leaders Should Attend Community Summit North America 2026
Next Article
Community Summit NA 2026: Recap

About Author

Samuel Mathew

Software developer acknowledged for talents conceptualizing and directing the development and continuous refinement of advanced technology solutions to meet clients’ needs. Sophisticated programming knowledge combines with well-honed problem-solving strengths to meet the challenges of business economics, client needs, and technical innovation.

Facebook Twitter LinkedIn

Related Posts

  • Why Technology Leaders Should Attend Community Summit North America 2026

    August 5, 2026
  • Understand Dynamics GP Lifecycle Policies

    December 2, 2024
  • Error : “The selected company is not configured as a company of the current Microsoft Dynamics GP system database. You must resolve the database configuration to log in to the company”

    April 10, 2018

Social Media

  • LinkedIn
  • Google
  • Facebook
  • Twitter
  • Pinterest

About Me!

Samuel Mathew

Software developer acknowledged for talents conceptualizing and directing the development and continuous refinement of advanced technology solutions to meet clients’ needs. Sophisticated programming knowledge combines with well-honed problem-solving strengths to meet the challenges of business economics, client needs, and technical innovation.

Subscribe to My Blog

🤞 Don’t miss these tips!
Stay updated with the latest insights on Microsoft Dynamics 365, AI, and technology leadership.

We don’t spam! Read our privacy policy for more info.

Check your inbox or spam folder to confirm your subscription.

Archives

  • October 2026
  • August 2026
  • July 2026
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • January 2023
  • April 2018
  • March 2018
  • February 2018
  • December 2017
  • November 2017
  • April 2017
  • January 2017
  • September 2016
  • June 2016
  • May 2016
  • April 2016
  • October 2015
  • February 2015
  • November 2014
  • February 2014
  • April 2013
  • March 2013

Categories

  • D365 Business Central
  • D365 Finance & Operations
  • Dexterity
  • Dynamics 365
  • Dynamics GP
  • Dynamics Summit NA
  • Fabric IQ
  • Featured
  • Franchisee Portal
  • General
  • GP 2018 Toolbox
  • Microsoft Fabric
  • Power BI
  • Royalty Management System
  • SQL Server

MVP BLOG LINKS

  • David Musgrave: Winthrop Development Consultants Blog

GitHub (AL Development)

  • dvlprlife (Brad)
  • dgpblogster (Mariano Gomez Bent)
  • ajansari (AJ Ansari)
  • microsoft/BCQuality
  • microsoft/AL-Go
  • microsoft/alguidelines
  • microsoft/BCTech
  • microsoft/ALAppExtensions
  • microsoft/AL
inD365 Business Central March 14, 2018

Announcing Microsoft Dynamics 365 Business Central

BySamuel Mathew
inDynamics GP February 10, 2015

Who actually uses the Dynamics GP Multi-Tenant feature?

BySamuel Mathew

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org
TAG CLOUD

AI Agents Azure Data Lake Business Central Community Summit D365F&O Security Development Dexterity Dynamics 365 Dynamics 365 F&O Dynamics Communites Dynamics GP Environment ERP Strategy ERP System Featured GP GP 2013 GP 2016 GP 2018 GP Web Client Installation Microsoft Copilot Microsoft Dynamics Microsoft Dynamics 365 BC Microsoft Fabric Microsoft SQL Server Migration from GP to Business Central Multi-tenant Power Platform Product LifeCycle Royalty & Rights Script SmartList SmartList Designer SQL Reporting Services SQL Script SQL Server Summit NA Synapse Analytics Technology Leadership Telemetry

Subscribe via RSS feed

Get the latest insights on Microsoft Dynamics 365 (GP, BC and F&SCM), AI, and Technology Leadership.

Subscribe via RSS

© Copyright 2020 Samuel Mathew.  All rights reserved.