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.

SQL
SELECT * FROM SYSOBJECTS

SYSOBJECTS

C#
select * from SYSDEPENDS

SYSDEPENDS

Steps

Create 3 tables named A , B and C.

SQL
create table A  
(  
  id int ,  
  address1 nvarchar(20)  
)  
  
create table B  
(  
  id int ,  
  address2 nvarchar(20)  
)  
  
create table C  
(  
  id int ,  
  address3 nvarchar(20)  
)

Create a procedure and mention 3 tables mentioned above, using inner joins.

SQL
Create procedure Sp_ListTables  
as   
begin  
set nocount on;  
select * from A   
inner join B on A.id = B.id  
inner join C on A.id = C.id  
end

Now, execute the procedure.

SQL
exec Sp_ListTables

EXEC SP

Using below mentioned important T-SQL query, we can get the list of the tables used in the stored procedure.

SQL
SELECT   
NAME as 'List Of Tables'  
FROM SYSOBJECTS  
WHERE ID IN (   SELECT SD.DEPID   
                FROM SYSOBJECTS SO,   
                SYSDEPENDS SD  
                WHERE SO.NAME = 'Sp_ListTables'  ----name of stored procedures  
                AND SD.ID = SO.ID  
            )

get the list of the tables used in the stored procedure

Here, I put two objects SYSOBJECTS, SYSDEPENDS and put some inner join on the columns of these two objects.

SQL
SELECT SD.DEPID   
                FROM SYSOBJECTS SO,   
                SYSDEPENDS SD  
                WHERE SO.NAME = 'Sp_ListTables'  ----name of stored procedures  
                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.