对一段SQL进行语法检查

下面的C#代码用来检查一段SQL语句的语法是否正确:

    public string CheckSQLCommand(string connectionString, string sql)
{
String message = null;

try
{
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
SqlCommand sqlCommand = sqlConnection.CreateCommand();
sqlCommand.CommandTimeout = 1;
sqlCommand.CommandText = "SET PARSEONLY ON;" + sql + ";SET PARSEONLY OFF;";
sqlCommand.ExecuteNonQuery();
}
}
catch (Exception ex)
{
if (ex.Message.IndexOf("Timeout") == -1)
{
SqlException sqlException = ex as SqlException;
if (sqlException != null)
{
if (sqlException.Number < 50000 && sqlException.Number != 2627)
{
message = ex.Message;
}
}
}
}

return message;
}
原文地址:https://www.cnblogs.com/zanxiaofeng/p/1687677.html