1

I am working on a database which has does a lot of stored procedures and tables.

One brute force way to know all the stored procedures and tables called by a single stored procedure is by scanning and reading through the code. However, it takes a lot of time.

what is the query to find out all the stored procedures and tables that are called by a main stored procedure?

1
  • To make the question clearer with example. Let's say stored procedure 1 (SP) calls SP2 and table 2, and SP2 calls SP3 and table 3. Could i run a query including SP1 to list SP2, table 2, SP3 and table 3? Commented May 25, 2015 at 9:08

1 Answer 1

2

You can query sys.objects and sys.sql_expression_dependencies tables like this:

SELECT sys.objects.name, sys.objects.type_desc FROM sys.sql_expression_dependencies INNER JOIN sys.objects ON(referenced_id = object_id) WHERE referencing_id = OBJECT_ID('<Your stored procedure name here>') 

Don't forget to replace <Your stored procedure name here> with the actual name of the stored procedure.

Update:
A stored procedure called from another stored procedure will still have a row in sys.sql_expression_dependencies, but will have a null value in the referenced_id column. you can use something like this:

DECLARE @StoredProcedureName sysname = '<Your stored procedure name here>' SELECT sys.objects.name, sys.objects.type_desc FROM sys.sql_expression_dependencies INNER JOIN sys.objects ON(referenced_id = object_id) WHERE referencing_id = OBJECT_ID(@StoredProcedureName) UNION ALL SELECT procedures.name , 'Stored Procedure' As type_desc FROM sys.sql_expression_dependencies INNER JOIN sys.procedures ON(referenced_entity_name = sys.procedures.name) WHERE referencing_id = OBJECT_ID(@StoredProcedureName) AND referenced_id IS NULL 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the query, i found all the tables called, including the joined tables, within the stored procedures using this solution. However, it does not detect "exec <sub stored procedures> portion" called by the main <stored procedure>. Is there a way to include stored procedures called?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.