Validate a SQL string in .NET [duplicate]
Solution 1:
If you want to validate SQL syntax without the use of a database, the TSql100Parser
class will do well for this situation.
Disclaimer, code borrowed from this post here Code to validate SQL Scripts
Pretty straightforward to use though. If it returns null, then there were no errors in parsing it.
using Microsoft.Data.Schema.ScriptDom;
using Microsoft.Data.Schema.ScriptDom.Sql;
public class SqlParser
{
public List<string> Parse(string sql)
{
TSql100Parser parser = new TSql100Parser(false);
IScriptFragment fragment;
IList<ParseError> errors;
fragment = parser.Parse(new StringReader(sql), out errors);
if (errors != null && errors.Count > 0)
{
List<string> errorList = new List<string>();
foreach (var error in errors)
{
errorList.Add(error.Message);
}
return errorList;
}
return null;
}
}
Solution 2:
Set your query to sql with this hint:
set PARSEONLY on
It just checks your query and returns, like this:
set PARSEONLY on
select * from tablea
Returns no exception.
While
set PARSEONLY on
select * f rom tablea
returns
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'f'.