Code to validate SQL Scripts

前端 未结 4 850
挽巷
挽巷 2020-11-28 08:19

How can I validate sql scripts before executing them using .net 2.0 and c#?

If the sql is not valid I want to return error rows.

4条回答
  •  情话喂你
    2020-11-28 08:38

    If you are creating a tool that allows the user enter some sql code by hand and you want to validate the code entered using C# code before execution on sql server, you can create a method like this:

    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;
            }
    }
    

    As of 2018 and new database versions, this might be newer version:

    using Microsoft.SqlServer.TransactSql.ScriptDom;
    

    (download with npm: PM> Install-Package Microsoft.SqlServer.TransactSql.ScriptDom -Version 14.0.3811.1 )

    public bool IsSQLQueryValid(string sql, out List errors)
    {
        errors = new List();
        TSql140Parser parser = new TSql140Parser(false);
        TSqlFragment fragment;
        IList parseErrors;
    
        using (TextReader reader = new StringReader(sql))
        {
            fragment = parser.Parse(reader, out parseErrors);
            if (parseErrors != null && parseErrors.Count > 0)
            {
                errors = parseErrors.Select(e => e.Message).ToList();
                return false;
            }
        }
        return true;
    }
    

提交回复
热议问题