Query validation using C#

后端 未结 4 1700
北荒
北荒 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<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;
            }
    }
    
    0 讨论(0)
  • 2020-12-06 00:57

    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'.
    
    0 讨论(0)
  • 2020-12-06 00:58

    If you would like to validate/parse just a SELECT statement, regardless of how "heavy-duty" that select statement is, I found out that the best and fastest way to validate a select statement is the following: - in your code create 2 select statements (strings) such as:

    1) Your valid select statement: SELECT * FROM HUGE_TABLE JOIN MULTIPLE_TABLES WHERE <<Condition>> 2) Create a similar select statement such as SELECT TOP 1 * FROM HUGE_TABLE JOIN MULTIPLE_TABLES WHERE <<Condition>> - Parse/Validate just the second one, regardless of how many joins you have in there, it will parse it in milliseconds, such as:

    SqlCommand sqlParse = new SqlCommand(ParseSelectStatement, sqlConn); 
    
    try 
    {
    sqlConn.Open();
    sqlParse.ExecuteNonQuery()
    }
    

    Hope it helps! Cheers!

    0 讨论(0)
  • 2020-12-06 01:02

    I think this is what you are looking for. http://www.codeproject.com/KB/database/sqlvalidator.aspx

    0 讨论(0)
提交回复
热议问题