To find invalid stored procedures in SQL Server, the fastest reliable technique is to scan every procedure—or the ones you care about—for references to objects that don’t exist and for compile errors, using system catalog views such as sys.sql_expression_dependencies and sys.dm_sql_referenced_entities, supplemented by a test compile (for example, sp_refreshsqlmodule or a SET NOEXEC ON pass). Microsoft SQL Server is the main platform discussed here because its catalog exposes these dependencies directly; the general principles carry over to other engines, but the exact queries don’t. “Invalid” itself covers two different problems: broken object references left behind by renames and drops, and syntax or binding errors that only a compile reveals.
Below, the steps run from a fast catalog scan to a full compile sweep, with checks at each stage so you can stop when the problem is found.
What “Invalid” Actually Means for a Stored Procedure
A stored procedure can be broken in several distinct ways, and each needs a different detection method. Mixing them up is the most common reason people miss problems.
Deferred name resolution is the root cause of most false confidence. When you create a procedure whose referenced table doesn’t exist yet, SQL Server allows it (the object name is resolved at first execution, not at creation). That means a procedure can sit in the database for months, look fine in management tools, and fail the moment someone calls it. Since SQL Server defers this check, CREATE PROCEDURE succeeding tells you almost nothing about validity.
Broken object references happen when a table or view a procedure depends on is dropped or renamed, or when a column the procedure uses is removed. The procedure text still points at the old name.
Compile-time errors include syntax mistakes, references to objects the procedure isn’t permitted to see, or binding problems that surface only when the module is recompiled.
Metadata staleness is subtler: a procedure may be logically fine but carry outdated dependency metadata, which throws off any tool that relies on that metadata.
A single catalog query can catch broken references to dropped objects. Catching column-level breakage or syntax errors requires forcing a compile. Use both, in that order.
Before You Start: Permissions and a Safety Baseline
You need permission to read definitions and dependency metadata—at minimum membership in a role that can see sys.sql_modules and execute sys.dm_sql_referenced_entities. In practice, db_owner or membership in the db_ddladmin/db_datareader combination with appropriate permissions usually works, but check against your organization’s least-privilege rules before running a broad sweep in production.
Two safety habits matter here:
Run read-only discovery queries during a low-traffic window if the database is large. Catalog queries are lightweight, but a compile sweep of thousands of procedures is not free. Run any query that recompiles modules (sp_refreshsqlmodule) in a non-production copy first, or accept that touching a procedure’s metadata can briefly affect its cached plan. sp_refreshsqlmodule doesn’t alter the procedure’s logic, but it does recompile it, and recompilation grabs brief schema locks.
Decide up front whether you’re auditing everything or only recently changed procedures. Most teams inherited hundreds or thousands of procedures and only a fraction are actively used, so an inventory-first approach saves time.
Step 1: Inventory the Procedures You’re Auditing
Start by listing the modules so you know your scope. This query returns each user-defined stored procedure with its schema, name, and create/modify dates:
Filter with p.modify_date >= '2026-01-01' if you only want procedures touched recently. Save the result as your work list. Expect the count to be large—production ERP and reporting databases commonly hold several thousand procedures—so treat the list as the population, not the answer.
A quick success check: the row count matches what you see when you expand the Programmability > Stored Procedures node in your management tool. If it doesn’t, your query is missing a schema or filtering on the wrong flag.
Step 2: Catalog-Scan for Missing Object References
This is the workhorse. sys.sql_expression_dependencies records, for each procedure, the objects its definition references by name, including the object ID it points at when that could be resolved. When a table is dropped, the dependency row remains but the referenced object ID becomes null or points at nothing—so a join to sys.objects fails.
Read the results carefully. referenced_id IS NULL means SQL Server could not bind that name to an object at scan time. Usually that’s a dropped or renamed table or view. But two benign cases also produce null IDs: references to temporary tables (#temp) and references to objects in other databases that are currently offline or not visible to your session. To reduce noise, exclude names starting with #:
A second catalog table, sys.sql_dependencies (the older, deprecated one), behaves differently and is retained for backward compatibility; rely on sys.sql_expression_dependencies for new work.
What this step can’t see: broken column references when the table itself still exists. If someone dropped a column, the procedure still lists the table as a resolved dependency, so it won’t appear here. That’s why Step 5 exists. Also note that catalog metadata can be stale—if a bug or an improper restore left dependency rows out of sync, this scan misses the break. Forcing a refresh (Step 6) resolves that class of false negative.
Success check: pick one flagged procedure, open its definition, and search for the missing object name. If you find a SELECT ... FROM dbo.OldTable and dbo.OldTable isn’t in sys.tables, the flag is real.
Step 3: Test-Compile Candidates to Confirm Breakage
Catalog hits tell you where to look, not always what’s wrong. Confirm each suspect by forcing a compile. sys.sp_refreshsqlmodule does exactly that for one module: it recompiles the stored procedure’s metadata and throws an error if the definition can’t bind.
If the procedure compiles, it produces an error; if it compiles cleanly, it returns silently. You can test a batch of candidates by cursor or by generating calls, but do it in a test environment—and note that refresh succeeds even for procedures with unresolved names in some cases, so treat a silent refresh as “no compile error,” not a guarantee of validity. A related system procedure, sp_refreshview, does the same job for views that procedures rely on; a broken view can make a procedure invalid even when the procedure text is fine.
Expect an error message such as “Invalid object name ‘dbo.OldTable’” or “Could not find prepared statement with handle…”. The message text identifies the offending object, which is your repair target.
Stop condition: if the compile error concerns permissions on objects outside your control, or involves linked-server or cross-database references, pause and involve the DBA or platform owner rather than granting yourself access to fix it.
Step 4: Handle Procedures That Use Encrypted or Obfuscated Definitions
WITH ENCRYPTION procedures are a blind spot for every catalog-based approach. Their definition text isn’t readable, and dependency metadata may be limited or absent. This is a known limit, not a bug. Two practical responses:
Maintain a source-controlled copy of every procedure, so you can diff deployed encrypted modules against the repository. If your team has always kept definitions in version control, the repository is your reference truth even when the database won’t show you the text. Flag encrypted modules during inventory (the sys.sql_modules.definition column is null) so you don’t mistake “no findings” for “clean.” Add a WHERE definition IS NULL check to your inventory and record those procedure names for a manual ownership review.
Also be aware that schemabound procedures (created WITH SCHEMABINDING) can’t be altered while dependent objects change, which largely prevents them from going invalid silently—so you can deprioritize them in your sweep.
Step 5: Compile in an Isolated Safety Net with SET NOEXEC
For a broader compile sweep without executing the procedure bodies, set NOEXEC mode and then run each definition, or generate EXEC statements for all candidates with NOEXEC on. In SET NOEXEC ON mode, SQL Server parses, resolves, and compiles statements but does not execute them.
Be deliberate with this technique. NOEXEC compiles but, importantly, a procedure invoked with EXEC in that mode can still cause side effects through deferred compilation and early statement checks—so treat it as a compile test, not a true sandbox. The safer variant is to skip EXEC and instead recreate the procedure’s body in a transaction on a test copy. Either way, the signal you want is a binding error message, and the required discipline is that you never run this against production without a rollback plan.
If you prefer a single-script approach, many teams generate a BEGIN TRY … END TRY / BEGIN CATCH wrapper around each EXEC and log errors to a table. That turns a manual sweep of hundreds of procedures into a one-time job whose output lists every invalid module with its error.
Step 6: Refresh Metadata So Future Scans Stay Accurate
If your Step 2 results look suspiciously clean or suspiciously noisy—for example, a procedure clearly references a missing table but doesn’t appear—the dependency metadata may be stale. sp_refreshsqlmodule on each procedure (and sp_refreshview on views) rebuilds that metadata. Run it across all procedures in a test copy first, record any errors, and then re-run the Step 2 query. The refreshed run gives you a cleaner list.
A concrete sequencing tip: refresh views first when a procedure depends on views. A view that references a dropped table will keep its own dependency rows stale, and refreshing the view can surface the breakage that the procedure’s catalog scan reported as clean.
Handling the Findings: Common Causes and Fixes
Once you have a confirmed list, the repairs cluster into predictable categories:
Dropped or renamed tables and views. The fix is either to restore/rename the object or to update the procedure to reference the current name. If the rename was intentional, search the procedure text for the old name and correct it. Use ALTER PROCEDURE rather than editing a catalog.
Removed columns. This is the failure mode catalog scans miss. The procedure lists the table as a dependency but references a column that no longer exists; only a compile (Steps 3–5) catches it. Search each procedure definition (OBJECT_DEFINITION(object_id)) for column names that are absent from sys.columns.
Renamed procedures called from other procedures. A procedure calling EXEC dbo.OldName is itself invalid, and it also shows up as a dependency reference. Fix the caller.
Cross-database references to offline databases. These show as null IDs but aren’t really broken procedures. Confirm by checking whether the referenced database exists and is online (sys.databases.state_desc); if the dependency is intentional and the database comes online soon, leave it.
Encrypted definitions. As in Step 4, these need source-repository comparison, not catalog queries.
For each fixed procedure, re-run the compile test to confirm it now passes. One passing check after repair matters: sp_refreshsqlmodule returning silently is your success signal, and a re-run of the Step 2 query not returning that procedure confirms the dependency gap is closed.
Turning This Into a Repeatable Audit
A one-time hunt leaves you exposed next sprint. Two lightweight habits keep invalid procedures from accumulating:
1: Schedule the catalog scan. Run the Step 2 query weekly as a job and route any hits to the owning team. The query is cheap, and the output is short. 2: Add a compile test to deployment. After any release that alters tables or views, run sp_refreshsqlmodule across the procedures in that subsystem. A silent refresh is a pass; an error blocks the deployment.
Order matters: refresh views before procedures, and re-scan after refreshes. Log the results so you can tell a transient cross-database offline event from a genuine rename. Treat the inventory from Step 1 as the authoritative list and keep it in version control; that repository also becomes your fallback for encrypted modules and your reference when dependency metadata is suspect.
The limits are worth stating plainly. The runtime cost of a compile sweep scales with procedure count and definition complexity, so a database with tens of thousands of procedures may need batching by schema. Catalog metadata can lag after certain restores or bulk operations. Encrypted and cross-database modules will always need a different verification path. Within those limits, the sequence—inventory, catalog scan, confirm by compile, refresh, repair, repeat—catches both the obvious broken references and the column-level breakage that a simple scan misses.