none
How to check SQLquery syntax is valid or not using c# ? RRS feed

  • Question

  • Hi all 

    I was trying to do some kind of query optimization tree using C# .reading any query statement from user and then do some operations over it. but what i can't did was to check if this query is valid or not in other words i want to do something like Sqlsever parser to check query syntax without need to connect to SQLserver because this query is virtual query i have not any Tables or DataBases i just working in the query as it .

    please if any one can help . 

    Thanks.

    Tuesday, April 27, 2010 6:09 PM

All replies

  • it is a sql server trick

     

    you could run such a query

     

    SET NOEXEC ON

    sql query

    SET NOEXEC OFF

     

    --------------

     

    this will not run the query but you could get the result and control it if it contains an error message or not


    http://www.sdtslmn.com
    Tuesday, April 27, 2010 6:17 PM
  • you mean in sqlserver!!!  but i do not want to deal with sqlserver all i want to do with c# code is to check syntax of the query is valid or not ! Note : I am using VS2005
    Tuesday, April 27, 2010 6:53 PM
  • this in c++ i need it c# code an i have not this API in c#
    Tuesday, April 27, 2010 7:20 PM
  • Oh - Sorry I didn't check that

    Karl


    http://unlockpowershell.wordpress.com
    Tuesday, April 27, 2010 7:50 PM
  • you mean in sqlserver!!!  but i do not want to deal with sqlserver all i want to do with c# code is to check syntax of the query is valid or not ! Note : I am using VS2005

    This is an old post, but it's the answer I was looking for.

               using (SqlConnection cn = new SqlConnection(myConnString))
                {
                    cn.Open();
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.Connection = cn;
                        cmd.CommandType = System.Data.CommandType.Text;
                        cmd.CommandText = "SET NOEXEC ON;" + mySQLStmtToTest + ";SET NOEXEC OFF";
                        try
                        {
                            cmd.ExecuteNonQuery();
                            label1.Text = "Success";
                        }
                        catch
                        {
                            label1.Text = "Fail";
                        }
                    }
                }

    Sunday, April 28, 2019 1:45 PM
  • I can see you can do some basic syntax checking without the underlying database.  However to really check SQL and where most errors are you need access to database schema and data in database.  How do you check referential integrity, data types or index integrity with the database or data?  
    Sunday, April 28, 2019 6:32 PM