http://social.msdn.microsoft.com/Forums/en-US/sqlnetfx/thread/fbcb255f-bcb7-45d8-9991-270a329b3d51/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Data.Schema.ScriptDom;
using Microsoft.Data.Schema.ScriptDom.Sql;
using System.IO;
namespace ConsoleApplication27
{
class SqlPareCenter
{
TSql100Parser parser;
public SqlPareCenter()
{
parser = new TSql100Parser(false);
}
public List<FieldInfo> GetSQLFields(string query)
{
IList<ParseError> errors;
IScriptFragment result = parser.Parse(new StringReader(query), out errors);
List<FieldInfo> list = new List<FieldInfo>();
TSqlStatement statement = ((TSqlScript)result).Batches[0].Statements[0];
foreach (var item in (((QuerySpecification)((SelectStatement)statement).QueryExpression).SelectElements))
{
SelectColumn c = (SelectColumn)item;
string alias = c.ColumnName == null ? "" : GetStringFromTSqlFragment(query, c.ColumnName);
string express = GetStringFromTSqlFragment(query, item);
list.Add(new FieldInfo() { Alias = alias, Express = express });
Console.WriteLine(alias + " : " + express);
//Console.WriteLine(GetStringFromTSqlFragment(query, item) + " Alias: " + (c.ColumnName == null ? "" : GetStringFromTSqlFragment(query, c.ColumnName)));
}
return list;
}
private string GetStringFromTSqlFragment(string wholeStatementString, TSqlFragment fragment)
{
return wholeStatementString.Substring(fragment.StartOffset, fragment.FragmentLength);
}
}
}