我正在寻找使用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
}
}
}
}
答案 0 :(得分:0)
SelectScalarExpression
具有ColumnName
属性,该属性与ColumnReferenceExpression
处于同一级别。如果该列上没有别名,则为null。
您的循环可能包含以下内容:
if (column is SelectScalarExpression)
{
var columnAlias = (column as SelectScalarExpression).ColumnName?.Value;
if (columnAlias == null)
{
// evaluate the ColumnReferenceExpression here
}
}