How to get SelectStatement from Procedure?

2019-08-30 04:38发布

问题:

This is a follow up question from here. I'm trying to use DACExtensions to retrieve the SelectStatement objects from a Procedure so that I can generate wrapper functions from my SSDT project using a T4 template. The problem is that the Nodes property of my Visitor object doesn't have any nodes in it. What am I missing?

Here's my Visitor:

public class SelectVisitor : TSqlFragmentVisitor
{
    public SelectVisitor() { this.Nodes = new List<SelectStatement>(); }
    public List<SelectStatement> Nodes { get; private set; }
    public override void Visit(SelectStatement node)
    {
        base.Visit(node);
        this.Nodes.Add(node);
    }
}

And here is how I'm trying to use it:

// Create the model
var procFiles = Directory.GetFiles(sqlPath, "*.sql", SearchOption.AllDirectories);
var model = new TSqlTypedModel(SqlServerVersion.Sql100, new TSqlModelOptions());
foreach(var procFile in procFiles)
{
    model.AddObjects(File.ReadAllText(procFile));
}

// Loop through the procs
var procs = model.GetObjects<TSqlProcedure>(DacQueryScopes.UserDefined);
foreach(var proc in procs){ 
    var selectVisitor = new SelectVisitor();
    var ast = proc.GetAst();
    ast.Accept(selectVisitor);
    foreach(var node in selectVisitor.Nodes){
        // Nodes has Count=0 :(
    }
}

回答1:

Using TSqlModelUtils.TryGetFragmentForAnalysis should ensure you get the original AST inside the model - hopefully that will have what you need. You may want to debug in and view your AST and what actually gets created - that's how we do things internally and often you may be surprised about what actually gets generated. Finally note that the DacpacExplorer tool might make this easier to visualize - it should now have support for showing the AST behind an object such as a procedure.