Get a list of tables used in Procedures, Procedures used by Table

In this blog, I have explained the following concepts:
  • How to get a list of tables used in Procedure.
  • How to get a list of Procedures, Functions and Views used by table.

Run the following script in your database, it will create the USP_GetTableByProcedure procedure. The procedure accepts two optional parameters: @ProceureName and @TableName. If you provide procedure name, it lists all the tables which are used in that procedure. If you provide table name, then you will get all the procedures which are used in the table.

  1. Create procedure USP_GetTableByProcedure  
  2. @ProceureName varchar(50)=Null,  
  3. @TableName varchar(50)=Null  
  4. AS  
  5. BEGIN  
  6.     SELECT DISTINCT O.NAME AS 'Procedure_Name' , OO.NAME AS 'Table_Name'
  7.     FROM SYSDEPENDS D, SYSOBJECTS O, SYSOBJECTS OO  
  8.     WHERE   O.ID=D.ID   
  9.             AND O.NAMEISNULL(@ProceureName,O.NAME)  -- STORED PROCEDURE NAME  
  10.             AND OO.ID=D.DEPID   
  11.             AND OO.NAME = ISNULL(@TableName,OO.NAME-- Table PROCEDURE NAME
  12.     ORDER BY O.NAME,OO.NAME  
  13. END 
 Testing : Test the above stored procedure in the following two ways:
  1. Execute the Stored Procedure by passing stored procedure name to get the tables that are used in.

  2. Execute the Stored Procedure by passing table name to get the procedure that is used by.

According to my database I use Mas_Table table and  USP_Get_AllTeams procedures as parameters -

Step 1: Exec USP_GetTableByProcedure 'USP_Get_AllTeams' , Null.
 
 
In the above output as you can see the list of tables that are used in USP_Get_AllTeams procedure.
 
Step 2: Exec USP_GetTableByProcedure Null , 'Mas_Team'.
 
 
In the above output as you can see the list of procedures that are used with Mas_Table.
I hope you enjoyed it.
Ebook Download
View all
SQL Jobs
Read by 0 people
Download Now!
Learn
View all