'How to find column names which used for joining tables?

I have a stored procedure for a select query and there are left join and inner join commands in the query. I'm using the script below for dependencies of the stored procedure.

select  
    referenced_database_name,
    referenced_entity_name,
    referenced_minor_name
from 
    sys.dm_sql_referenced_entities ('dbo.sp_test', 'OBJECT')

How can I get the column name which used for joining tables in this SP? Or is there any simple way to get/parse column names from this script:

select column1, column2
from tableA
inner join tableB on tableB.id = tableA.id

I need tableB.id and tableA.id keywords from the script

I've tried parse that script with substring, left etc functions but they're insecure for me. There are lots of piece of select query using union all.



Solution 1:[1]

I'v solved my problem parsing the query. At first, i left a delimiter (--*) for splitting the section which contains joins then used that code for parsing the query (i know its not professional but it has worked for me) :

select distinct
referenced_database_name,
referenced_entity_name,
referenced_minor_name,
SUBSTRING(c.value,CHARINDEX('on',value)+3,len(value)) split
,IIF(SUBSTRING(c.value,CHARINDEX('on',value)+3,len(value)) like '%'+CONCAT(referenced_entity_name,'.',referenced_minor_name)+'%',1,0) as clm
from sys.dm_sql_referenced_entities ('dbo.sp_test', 'OBJECT') a
left join sys.sysdepends b on OBJECT_NAME(depid) = a.referenced_entity_name
outer apply string_split(REPLACE(OBJECT_DEFINITION(id),'--*','/'),'/') c
where OBJECT_NAME(id) = 'sp_test' and c.value like '%join%' and referenced_minor_name is not null

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1