Parsing a SQL string in c#

Willem picture Willem · Sep 16, 2011 · Viewed 9.2k times · Source

I have the need to Parse a Command.CommandText.

I don't want to run the query. I only want to see if the query will succeed if the command was executed.

Say i have; "SELECT * FROM SomeTable WHERE (1=1)"

This string will succeed.

but,

"SELECT * FROM SomeTable WHERE (1=1"

will not succeed.

Now my question. How would i Parse this string c#?

Answer

Martin Smith picture Martin Smith · Sep 16, 2011

If you just want to validate the syntax. You can use Microsoft.Data.Schema.ScriptDom for this.

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

.....

        string sql = "SELECT * FROM SomeTable WHERE (1=1";
        var p = new TSql100Parser(true);
        IList<ParseError> errors;

        p.Parse(new StringReader(sql), out errors);


        if (errors.Count == 0)
            Console.Write("No Errors");
        else
            foreach (ParseError parseError in errors)
                Console.Write(parseError.Message);