Would like to create analysis for queries in SQL Server which will be checking which tables were join on which tables on which columns. Would like to use ScriptDom in C#. For example we have query:
SELECT *
FROM tabel1
INNER JOIN tabel2 ON tabel1.varchar1col = tabel2.varchar1col
INNER JOIN tabel3 ON tabel1.varchar2col = tabel3.varchar2col
LEFT JOIN tabel4 ON tabel3.varchar2col = tabel4.varchar3col
And would like to have result:
tabel1 varchar1col
tabel1 varchar2col
tabel2 varchar1col
tabel3 varchar2col
tabel4 varchar3col
Is it possible to create it in ScriptDom?
As discussed in comments, the parser does not actually resolve column names referenced in JOIN/WHERE clause predicates to objects in the query. Consider a syntactically valid query can reference invalid tables/aliases, unqualified names are ambiguous, plus constructs like CTEs, and derived tables, etc. present a challenge.
The example PowerShell script below (which you can convert to your .NET language of choice) uses a script DOM visitor. This will provide the desired results for the query in your question because the column names qualified with the actual table name. For more generalized use, predicates would need to consistently specify a 2-part name that reference a table (not alias, CTE, derived table, etc.).
Note that visitors in PowerShell need the script DOM assembly loaded before the derived class will compile. This can be done with a wrapper script like the example below that loads the assembly and dot-sources the script with the above visitor code. I cheated here and used the assembly included with the latest SSMS version. One should generally the assembly included in the DacFX NuGet package .
Results: