Skip to content

Instantly share code, notes, and snippets.

@mgroves
Created May 2, 2012 18:50
Show Gist options
  • Select an option

  • Save mgroves/2579162 to your computer and use it in GitHub Desktop.

Select an option

Save mgroves/2579162 to your computer and use it in GitHub Desktop.
public class ParsedSqlSelectQuery
{
public IList<string> SelectElements { get; private set; }
public string WhereClause { get; private set; }
public string FromClause { get; private set; }
public ParsedSqlSelectQuery(string sqlQuery)
{
var parser = new TSql100Parser(false);
IList<ParseError> errors;
var parsedQuery = parser.Parse(new StringReader(sqlQuery), out errors) as TSqlScript;
if (errors.Count > 0)
throw new ArgumentException("Errors in parsing tSQL: " + string.Join("\n", errors.Select(e => e.Message).ToArray()));
if (parsedQuery == null)
throw new ArgumentException("Invalid tSQL script: " + sqlQuery);
if (parsedQuery.Batches.Count != 1)
throw new ArgumentException("Only 1 batch supported");
if (parsedQuery.Batches[0].Statements.Count != 1)
throw new ArgumentException("Only 1 statement supported");
var selectQuery = parsedQuery.Batches[0].Statements[0] as SelectStatement;
if(selectQuery == null)
throw new ArgumentException("Only SELECT queries are supported");
var querySpecification = (QuerySpecification) selectQuery.QueryExpression;
SelectElements = querySpecification.SelectElements.Select(e => GetText(e, sqlQuery)).ToList();
if(querySpecification.WhereClause != null)
WhereClause = GetText(querySpecification.WhereClause, sqlQuery);
FromClause = string.Join(" ", querySpecification.FromClauses.Select(e => GetText(e, sqlQuery)).ToArray());
}
string GetText(TSqlFragment fragment, string sqlQuery)
{
var result = sqlQuery.Substring(fragment.StartOffset, fragment.FragmentLength);
return result;
}
}
@spetryjohnson
Copy link
Copy Markdown

Looks pretty clean... is TSql100Parser part of EF?

@mgroves
Copy link
Copy Markdown
Author

mgroves commented May 2, 2012

It's in these namespaces:

using Microsoft.Data.Schema.ScriptDom;
using Microsoft.Data.Schema.ScriptDom.Sql;

Not part of EF as far as I know.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment