microsoft / SqlScriptDOM

ScriptDOM/SqlDOM is a .NET library for parsing T-SQL statements and interacting with its abstract syntax tree

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

TSqlParser160 class fails to extract nested SelectStatements

adita15 opened this issue · comments

  • ScriptDom version: 150.4897.1
  • DacFx Version: 161.8089.0
  • .NET Framework (Windows-only) or .NET Core: 6.0
  • Environment (local platform and source/target platforms): Windows

Snippet:

str query = "SELECT [account_id] from [Account] WHERE [accounit_id] IN (SELECT [parent_account_id] FROM [ParentAccount])"
IList<ParseError> errors = null;
TSql160Parser parser = new TSql160Parser(false, SqlEngineType.All);
using (var rdr = new StringReader(query))
            {     
                TSqlScript tree = (TSqlScript)parser.Parse(rdr, out errors);
                MyVisitor visitor= new MyVisitor();
                tree.AcceptChildren(visitor);
            }

public class MyVisitor : TSqlFragmentVisitor
    {
        public override void Visit(TSqlFragment fragment)
        {
           base.Visit(fragment);
           Console.WriteLine("{0} visited as SelectStatement at line {1}, column {2}, length {3}", fragment.GetType().Name, fragment.StartLine, fragment.StartColumn, fragment.FragmentLength);
        }
   }

This results in "SelectStatement" count 1. Does not take into account nested select statement.
(DacFx/SqlPackage/SSMS/Azure Data Studio)

@adita15 @namangupta211 @zijchen this is not a bug. The "nested" SELECT is actually a subquery, and in ScriptDom it is parsed as a ScalarSubquery element. To visit the subquery please add a separate visitor for ScalarSubquery. The behavior is consistent across parser versions.