SQL SERVER – Find Stored Procedure Related to Table in Database – Search in All Stored Procedure

Following code will help to find all the Stored Procedures (SP) which are related to one or more specific tables. sp_help and sp_depends does not always return accurate results. Each option below returns every stored procedure related to table names you put in the LIKE filter.

Red threads running from a pin in a small table out to cards pinned around it, with a magnifying glass over one thread.

----Option 1
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%tablename%'
----Option 2
SELECT DISTINCT o.name, o.xtype
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
WHERE c.TEXT LIKE '%tablename%'

The version I would write today

syscomments and sysobjects are compatibility views. They still work, and they will for a long while yet, but Microsoft replaced them with the sys catalog views many versions ago. Here is the same search written the modern way.

SELECT s.name AS SchemaName,
       o.name AS ObjectName,
       o.type_desc AS ObjectType
FROM sys.sql_modules AS m
INNER JOIN sys.objects AS o ON m.object_id = o.object_id
INNER JOIN sys.schemas AS s ON o.schema_id = s.schema_id
WHERE m.definition LIKE '%YourTableName%'
ORDER BY o.type_desc, s.name, o.name;

This finds procedures, views, functions and triggers all at once, and type_desc tells you which is which. Drop the WHERE clause on type and you have a search across everything that holds SQL in your database.

The bug in the old approach that nobody mentions

This one caught me years ago and it is worth knowing. syscomments does not store a long procedure as one piece of text. It chops it into chunks of four thousand characters and stores them as separate rows.

So if your table name happens to land across the join between two chunks, the LIKE never matches and the procedure simply does not appear in your results. You get a clean list with nothing obviously wrong, and one procedure quietly missing. On a long procedure that is not a rare accident, it is just luck.

sys.sql_modules stores the definition in one piece, so the problem goes away. That, more than tidiness, is why I moved over.

The proper answer: ask SQL Server what depends on what

Searching text is a blunt instrument. SQL Server actually tracks dependencies, and since SQL Server 2008 there is a reliable view for it.

SELECT OBJECT_SCHEMA_NAME(d.referencing_id) AS SchemaName,
       OBJECT_NAME(d.referencing_id) AS ReferencingObject,
       o.type_desc AS ObjectType
FROM sys.sql_expression_dependencies AS d
INNER JOIN sys.objects AS o ON d.referencing_id = o.object_id
WHERE d.referenced_entity_name = 'YourTableName'
ORDER BY o.type_desc, ReferencingObject;

This is what replaced sp_depends, and it is the one to reach for when the question is “what will break if I change this table”. It understands that the name is a table rather than just a run of letters, so none of the false matches below apply to it.

There is a simpler wrapper around the same idea if you prefer.

SELECT referencing_schema_name, referencing_entity_name, referencing_class_desc
FROM sys.dm_sql_referencing_entities('dbo.YourTableName', 'OBJECT');

Why a plain search gives you answers that are not true

Searching for ‘%Orders%’ with LIKE will happily return:

Procedures that mention Orders only in a comment. Procedures that use a completely different table called OrderDetails or WorkOrders, because your text appears inside the longer name. Procedures that mention it in a string, in a print statement, or in code that was commented out five years ago and never removed.

None of those actually depend on your table, and if you are about to rename a column, that difference matters. Use the dependency view for the real answer, and keep the text search for when you genuinely want to find every place a word is written.

Searching every database at once

The queries above look at one database. If you are hunting for a table across a whole server, run it per database rather than writing something clever. A short loop is fine, but honestly, running it three or four times by hand is usually quicker than debugging a script that walks every database and trips over the one that is offline.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.

SQL Scripts, SQL Stored Procedure, SQL Utility
Previous Post
SQL SERVER – Cursor to Kill All Process in Database
Next Post
SQL SERVER – Fix : Error 14274: Cannot add, update, or delete a job (or its steps or schedules) that originated from an MSX server. The job was not saved.

Related Posts

167 Comments. Leave new

  • Frankie Resto
    March 6, 2018 11:27 pm

    Thanks for all your help.

    Reply
  • Hi Pinal, Your options are pulling extra records where that table is NOT present. E.g. I was looking for Table “Device” and also we have Column “DeviceID” in other table. Your options were pulling records for DeviceID as well. I found below code more reliable. But you are the best judge.

    select distinct [Table Name] = o.Name, [Found In] = sp.Name, sp.type_desc
    from sys.objects o inner join sys.sql_expression_dependencies sd on o.object_id = sd.referenced_id
    inner join sys.objects sp on sd.referencing_id = sp.object_id
    and sp.type in (‘P’, ‘FN’)
    where o.name = ‘Device’
    order by sp.Name

    Reply
    • Your solution is using catalog view and would be better to use when dependencies in catalog view is correctly populated. I am querying raw text of code using syscomments.

      Reply
  • Boyapati Yamini Kumar
    May 17, 2018 12:49 pm

    Your solutions works, thank you so much, but i also have a requirement to pass multiple tables as combination and retrieve the Stored Procedures. Thanks in Advance!

    Reply
  • thank u so much , now is was working good

    Reply
  • RAGHU NANDIKOTKUR
    November 8, 2018 2:01 am

    use sp_depends

    Reply
  • Hi Pinal, why sp_depends is not reliable for this as you mentioned.

    Reply
  • I would like to know number of result set should return in specific stored procedure.
    Is it possible to find total resultset (Datatable) returning from StoredProcedure?

    Reply
  • This is fine. But the problem with the LIKE is that if I have a table named Employees and a table named EmployeesPhones, when I look for Employees I’m obtaining the SPs for both tables

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.