Query validation using C#

后端 未结 4 1704
北荒
北荒 2020-12-06 00:40

I am looking for a query validator in C#, which allows me to parse the SQL text from a textbox and verify whether it\'s correct or not before sending it for execution (MS SQ

4条回答
  •  执念已碎
    2020-12-06 00:49

    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 Parse(string sql)
            {
                TSql100Parser parser = new TSql100Parser(false);
                IScriptFragment fragment;
                IList errors;
                fragment = parser.Parse(new StringReader(sql), out errors);
                if (errors != null && errors.Count > 0)
                {
                    List errorList = new List();
                    foreach (var error in errors)
                    {
                        errorList.Add(error.Message);
                    }
                    return errorList;
                }
                return null;
            }
    }
    

提交回复
热议问题