In order to use this script, you should have a table named dbo.CommandList. In my example, this table contains:
-
ServerName: the name of the linked server in which the query might run.
-
DBName: the Database in which the query might run.
-
SQLCommand: the query for which the script will find the dependencies.
What the script basically does is accessing the server (assuming the linked server works) and creates temporary stored procedure for the dynamic SQL. After creation, it finds its dependencies through sys.dm_sql_referenced_entities DMF.
I've tried several techniques to retrieve dynamic SQL's dependencies, and this was the only one which actually worked.
Feel free to modify the script to work with Dynamix SQL in variables and not tables, and keep in mind that sys.dm_sql_referenced_entities works only in SQL Server 2008 +. For older versions you should use other DMV's.