带有别名的SELECT的ScriptDom解析

时间:2018-11-12 20:16:45

标签: c# sql .net scriptdom

我正在寻找使用ScriptDom解析T-SQL语句并确保至少指定两列。我找到了一种提取列名的方法,并且可以从中正确地进行验证。但是,我也想验证列是否被别名,并且不确定如何检查。

我要确保select语句同时指定MCA和MOC列。

// this should pass
var sql = "SELECT MCA, MOC
FROM myTable";

// this should also pass
var sql = "SELECT some_col as MCA, some_other_col as MOC
FROM myTable";

_parser = new TSql120Parser(false);
var reader = new StringReader(sql);
var statements = parser.ParseStatementList(reader, out _errors);
var firstStatement = statements[0];
var select = firstStatement as SelectStatement;

var querySpec = statement.QueryExpression as QuerySpecification;
var columns = querySpec.SelectElements;
foreach(var column in columns) {
  if (column is SelectScalarExpression) {
    var expression = (column as SelectScalarExpression).Expression;
    if (expression is ColumnReferenceExpression) {
      var columnExpression = expression as ColumnReferenceExpression;
      if (identifier.Identifiers.Count == 1)
      {
        var columnName = identifier.Identifiers.First().Value;
        // I can validate from this extracted column name
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

SelectScalarExpression具有ColumnName属性,该属性与ColumnReferenceExpression处于同一级别。如果该列上没有别名,则为null。

您的循环可能包含以下内容:

if (column is SelectScalarExpression)
{
    var columnAlias = (column as SelectScalarExpression).ColumnName?.Value;

    if (columnAlias == null)
    {
        // evaluate the ColumnReferenceExpression here
    }
}