Find List Of Tables Used In Stored Procedure Using Types Of Joins

Introduction

Using SQL query, we can find out the list of the tables used in the stored procedure, using types of joins like inner join, outer join etc.

Description

Using SYSOBJECTS and SYSDEPENDS, we can get all the tables, stored procedure and other database object-related information. 
  1. SELECT * FROM SYSOBJECTS 
  1. select * from SYSDEPENDS  
 
 
Steps

Create 3 tables named A , B and C. 
  1. create table A  
  2. (  
  3.   id int ,  
  4.   address1 nvarchar(20)  
  5. )  
  6.   
  7. create table B  
  8. (  
  9.   id int ,  
  10.   address2 nvarchar(20)  
  11. )  
  12.   
  13. create table C  
  14. (  
  15.   id int ,  
  16.   address3 nvarchar(20)  
  17. )  
Create a procedure and mention 3 tables mentioned above, using inner joins.
  1. Create procedure Sp_ListTables  
  2. as   
  3. begin  
  4. set nocount on;  
  5. select * from A   
  6. inner join B on A.id = B.id  
  7. inner join C on A.id = C.id  
  8. end 
Now, execute the procedure.
  1. exec Sp_ListTables 
 
 
Using below mentioned important T-SQL query, we can get the list of the tables used in the stored procedure. 
  1. SELECT   
  2. NAME as 'List Of Tables'  
  3. FROM SYSOBJECTS  
  4. WHERE ID IN (   SELECT SD.DEPID   
  5.                 FROM SYSOBJECTS SO,   
  6.                 SYSDEPENDS SD  
  7.                 WHERE SO.NAME = 'Sp_ListTables'  ----name of stored procedures  
  8.                 AND SD.ID = SO.ID  
  9.             ) 
 

Here, I put two objects SYSOBJECTS, SYSDEPENDS and put some inner join on the columns of these two objects.
  1. SELECT SD.DEPID   
  2.                 FROM SYSOBJECTS SO,   
  3.                 SYSDEPENDS SD  
  4.                 WHERE SO.NAME = 'Sp_ListTables'  ----name of stored procedures  
  5.                 AND SD.ID = SO.ID  
Summary

We learned about SYSOBJECTS and SYSDEPENDS in addition to learning the stored procedure, which is used in SQL query to get the table lists.
Ebook Download
View all
SQL Jobs
Read by 0 people
Download Now!
Learn
View all