How to get table & their alias names using Microsoft ScriptDom library

39 Views Asked by At

Hi I am using Microsoft ScriptDOM parser (Microsoft.SqlServer.TransactSql.ScriptDom) to parse the SQL queries. For a decision making in my logic I want to know all the table names and their alias in a sql statement string (Basically a MERGE sql statement)

In below sql, I want to extract the table name and alias and store them into a dictionary as follows: [key: t_dpatch_parent , value: a] [key: t_dpatch_child , value: b]

MERGE INTO t_dpatch_parent a
USING t_dpatch_child b
ON (a.student_id = b.student_id)
WHEN MATCHED THEN
    UPDATE SET a.Proposed_Fee = b.collage_fee 

I have used this code but it is giving alias: null for table: t_dpatch_parent. It should add alias: a in this case

class TableAliasVisitor : TSqlFragmentVisitor
{
    private readonly Dictionary<string, string> _tableAliases = new Dictionary<string, string>();
    public Dictionary<string, string> TableAliases
    {
        get { return _tableAliases; }
    }
   

    public override void Visit(NamedTableReference node)
    {
        string tableName = node.SchemaObject.BaseIdentifier.Value;
        string tableAlias = node.Alias?.Value;
        _tableAliases[tableName] = tableAlias;
        
        base.Visit(node);
    }
}
0

There are 0 best solutions below